This is a short chapter on custom functions, so this will therefore be a short post. As you know, functions are the bread-and-butter of PHP code as they allow you to encapsulate repeatable code in a reusable manner, making the transition away from spaghetti code.
- Just like variable names, function names must only contain letters, numbers, and underscores while not starting with a number.
Return Values
- Funny thing about functions in PHP, they ALWAYS return something (NULL by default), there is no void (only ZUUL).
- Functions can be forced to return by reference by placing an ampersand (&) before the function name.
function &retRef() { }
-
</li>
-
</ul>
-
<h3>Functional Scope</h3>
-
<ul>
-
<li>All variables created in a function are destroyed upon exiting. </li>
-
<li>Variables declared outside of a function are not accessible inside unless passed by parameters or through use of the Global scope. </li>
-
<li><strong>Global scope</strong> (used through the global command or $GLOBALS superglobal array) allows variables to be read and modified inside a function without the need to pass as parameters.</li>
-
</ul>
-
<h3>Arguments</h3>
-
<ul>
-
<li>PHP will only yell at you if you provide<strong> too few arguments</strong> to a function.  In theory, you can provide as many arguments as you want as long as it is equal to or more than the arguments declared by the function.
-
<pre lang="php">function simple($one, $two) {}
-
-
simple($a, $b, $c, $d, $e);
-
- Arguments can be set as optional by providing a default value.
function optArguments($required, $optional = false) {}
-
</li>
-
<li>If you want a <strong>variable number of arguments,</strong> there are three functions designed to handle that.
-
<ul>
-
<li><strong>func_num_args():</strong> returns the number of arguments that were passed. </li>
-
<li><strong>func_get_arg($num):</strong> returns the value of the $num argument. </li>
-
<li><strong>func_get_args():</strong> returns an array of all the arguments. </li>
-
</ul>
-
<p>Here is an example: </p>
-
<pre lang="php">function varArgs() {
-
if (func_num_args() == 0)
-
return "Please provide at least ONE argument";
-
$args = func_get_args();
-
foreach ($args as $arg)
-
echo $arg."\n";
-
}
-
- Arguments can also be forced to be passed by reference by preceding them with the ampersand (&).
function passByRef(&$myArg) {
-
$myArg = 42;
-
}
-
Well, that was it for this chapter. Simple and straight to the point. Tomorrow I start chapter 3, Arrays. Woohoo!

