HTML and CSS Reference
In-Depth Information
User-Defined Functions
PHP enables you to create user-defined functions that, like JavaScript functions, enable
you to package up code you want to reuse. Here's how a function is declared:
function myFunction($arg = 0) {
// Do stuff
}
The function keyword indicates that you're creating a user-defined function. The name
of the function follows. In this case, it's myFunction . The rules for function names and
variable names are the same—numbers, letters, and underscores are valid. The list of
arguments that the function accepts follows the function name, in parentheses.
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();
On the other hand, $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.
 
 
Search WWH ::




Custom Search