Contents /
Previous /
Next
Functions
Any valid PHP code may appear inside user-defined functions,
even other functions and class definitions.
Functions need not be defined before they are referenced.
A function may be defined as follows:
function foo ($arg_1, $arg_2, ..., $arg_n) {
echo "Example function.\n";
return $retval;
}
Function arguments: Call by Value and by Reference
By default, function arguments are passed by value (so that if you
change the value of the argument within the function, it does not get
changed outside of the function).
To allow a function to modify its arguments, you must pass them by reference,
there are two possibilities to do that:
1) If you want an argument to a function to always be passed by
reference, you can prepend an ampersand (&) to the argument name in
the function definition:
function add_some_more(&$string) {
$string .= 'and more.';
}
$str = 'This is a string, ';
add_some_more($str);
echo $str; // outputs 'This is a string, and more.'
2) If you wish to pass a variable by reference to a function which does
not do this by default, you may prepend an ampersand to the argument
name in the function call:
function foo ($bar) {
$bar .= ' and more.';
}
$str = 'This is a string, ';
foo ($str);
echo $str; // outputs 'This is a string, '
foo (&$str);
echo $str; // outputs 'This is a string, and more.'
Default argument values
A function may define C++-style default values for scalar arguments as follows:
function makecoffee ($type = "cappuccino") {
return "Making a cup of $type.\n";
}
echo makecoffee ();
echo makecoffee ("espresso");
The default value must be a constant expression, not a variable.
Default arguments should be on the
right side of any non-default arguments.
Variable-Length Argument Lists
PHP supports variable-length argument lists,
using the functions:
int func_num_args():
Returns the number of arguments passed to the function.
mixed func_get_arg (int arg_num):
Return the arg_num'th item from the argument list.
array func_get_args():
Returns an array comprising a function's argument list.
No special syntax is required, and argument lists may still be
explicitly provided with function definitions and will behave as
normal.
Examples:
function foo() {
$numargs = func_num_args();
for( $i=0; $i < $numargs; $i++ ) {
echo "argument ".$i." is ".func_get_arg($i)."
";
}
}
foo(1, 2, 3);
function foo_array() {
$arg_list = func_get_args();
foreach( $arg_list as $num => $arg ) {
echo "argument ".$num." is ".$arg."
";
}
}
foo_array(1, 2, 3);
Return Values
Values are returned by using the optional return statement.
Any type may be returned, including lists and objects.
You cannot return multiple values from a function, but similar results
can be obtained by returning an (dynamic) array. Example:
function small_numbers() {
return array (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();
To return a reference from a function, you have to use the reference
operator & in both the function declaration and when assigning the
returned value to a variable:
function &returns_reference() {
return $someref;
}
$newref =&returns_reference();
This may be used to avoid an extra memcopy when returning
a large array.
Variable functions
PHP supports variable functions (like variable variables).
If a variable name has parentheses appended to it, PHP will look for a
function with that name and execute it.
This can be used to
implement callbacks, function tables, and so forth.
Example, try:
\n";
}
function bar( $arg = '' ) {
echo "In bar(); argument was '$arg'.
\n";
}
$func = 'foo';
$func();
$func = 'bar';
$func( 'test' );
?>
Anonymous = Temporary = Dynamic = Lambda-Style Functions
Anonymous functions are like C-style function pointers.
They may be used to create a function from
information gathered at run time.
create_function
creates an anonymous function from the parameters passed, and returns
a unique name for it:
string create_function (string args, string code)
Usually the args will be passed as a single
quote delimited string, and this is also recommended for the code. The
reason for using single quoted strings, is to protect the variable
names from parsing, otherwise, if you use double quotes there will be
a need to escape the variable names, e.g. \$avar.
Example:
$newfunc = create_function('$a,$b',
'return "ln($a) + ln($b) = ".log($a * $b);');
echo $newfunc(2,M_E)."\n";
Example, array of anonymous functions:
$f1 = 'if ($a >=0) {return "b*sqrt(a) = ".$b*sqrt($a);} else {return false;}';
$f2 = "return \"min(b^2+a, a^2+b) = \".min(\$a*\$a+\$b,\$b*\$b+\$a);";
$farr = array(
create_function('$a,$b', $f1),
create_function('$a,$b', $f2),
create_function('$x,$y', 'return "a hypotenuse: ".sqrt($x*$x + $y*$y);'),
);
process(2.3445, M_PI, $farr);
function process($var1, $var2, $farr) {
for ($f=0; $f < count($farr); $f++)
echo $farr[$f]($var1,$var2)."
";
}
An other common use for of anonymous functions is to create
callback functions, for example when using array_walk()or usort():
$av = array("the ","a ","that ","this ");
array_walk($av, create_function('&$v,$k','$v = $v."mango";'));
print_r($av);
outputs:
Array ( [0] => the mango [1] => a mango [2] => that mango [3] => this mango )
Function Handling Functions
bool function_exists (string function_name):
Checks the list of defined functions for function_name.
bool method_exists (object object, string method_name):
Checks if the class method exists.
array get_defined_functions ():
Returns an array of all defined
(internal and user defined) functions.
mixed call_user_func (string function_name [, mixed parameter [, mixed ...]])
:
Call a user function given by the first parameter.
This is equivalent to the "variable function" syntax.
See also: call_user_method().
mixed call_user_func_array (string function_name [, array paramarr])
:
Call a user function given with an array of parameters.
See also: call_user_method_array().
int register_shutdown_function (string func)
:
Registers the function named by func to be executed when script
processing is complete.