Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

User-Defined Functions 667

24


The preceding function has one argument, $arg. In this example, I’ve set a default value
for the argument. The variable $arg would be set to 0 if the function were called like
this:


myFunction();


However, $arg would be set to 55 if the function were called like this:


myFunction(55);


Functions can just as easily accept multiple arguments:


function myOtherFunction($arg1, $arg2, $arg3)
{
// Do stuff
}


As you can see, myOtherFunction accepts three arguments, one of which is an array.
Valid calls to this function include the following:


myOtherFunction('one', 'two', array('three'));
myOtherFunction('one', 'two');
myOtherFunction(0, 0, @stuff);
myOtherFunction(1, 'blue');


One thing you can’t do is leave out arguments in the middle of a list. So if you have a
function that accepts three arguments, there’s no way to set just the first and third argu-
ments and leave out the second, or set the second and third and leave out the first. If you
pass one argument in, it will be assigned to the function’s first argument. If you pass in
two arguments, they will be assigned to the first and second arguments to the function.


Returning Values


Optionally, your function can return a value, or more specifically, a variable. Here’s a
simple example of a function:


function add($a = 0, $b = 0) {
return $a + $b;
}


The return keyword is used to indicate that the value of a variable should be returned to
the caller of a function. You could call the previous function like this:


$sum = add(2, 3); // $sum set to 5


A function can just as easily return an array. Here’s an example:


function makeArray($a, $b) {
return array($a, $b);

Free download pdf