Tags
Functions
User-defined functions
A function may be defined using syntax such as the following:
Example: Pseudo code to demonstrate function uses
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
echo "Example function.\n";
return $retval;
}
Any valid PHP code may appear inside a function, even other functions and class definitions.
Function names follow the same rules as other labels in PHP. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.
Tip
See also the Userland Naming Guide.
Functions need not be defined before they are referenced, except when a function is conditionally defined as shown in the two examples below.
When a function is defined in a conditional manner such as the two examples shown. Its definition must be processed prior to being called.
Example: Conditional functions
$makefoo = true;
/* We can't call foo() from here
since it doesn't exist yet,
but we can call bar() */
bar();
if ($makefoo) {
function foo()
{
echo "I don't exist until program execution reaches me.\n";
}
}
/* Now we can safely call foo()
since $makefoo evaluated to true */
if ($makefoo) foo();
function bar()
{
echo "I exist immediately upon program start.\n";
}
Example: Functions within functions
function foo()
{
function bar()
{
echo "I don't exist until foo() is called.\n";
}
}
/* We can't call bar() yet
since it doesn't exist. */
foo();
/* Now we can call bar(),
foo()'s processing has
made it accessible. */
bar();
All functions and classes in PHP have the global scope – they can be called outside a function even if they were defined inside and vice versa.
PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions.
Note: Function names are case-insensitive, though it is usually good form to call functions as they appear in their declaration.
Both variable number of arguments and default arguments are supported in functions. See also the function references for func_num_args(), func_get_arg(), and func_get_args() for more information.
It is possible to call recursive functions in PHP. However avoid recursive function/method calls with over 100-200 recursion levels as it can smash the stack and cause a termination of the current script.
Example: Recursive functions
function recursion($a)
{
if ($a < 20) {
echo "$a\n";
recursion($a + 1);
}
}
Function arguments
Information may be passed to functions via the argument list, which is a comma-delimited list of expressions. The arguments are evaluated from left to right.
PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists are also supported, see also the function references for func_num_args(), func_get_arg(), and func_get_args() for more information.
Example: Passing arrays to functions
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
Making arguments be passed by reference ¶
By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.
To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition:
Example: Passing function parameters by reference
function add_some_extra(&$string)
{
$string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str; // outputs 'This is a string, and something extra.'
Default argument values
A function may define C++-style default values for scalar arguments as follows:
Example: Use of default parameters in functions
function makecoffee($type = "cappuccino")
{
return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
The above example will output:
Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.
PHP also allows the use of arrays and the special type NULL as default values, for example:
Example: Using non-scalar types as default values
function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL)
{
$device = is_null($coffeeMaker) ? "hands" : $coffeeMaker;
return "Making a cup of ".join(", ", $types)." with $device.\n";
}
echo makecoffee();
echo makecoffee(array("cappuccino", "lavazza"), "teapot");
The default value must be a constant expression, not (for example) a variable, a class member or a function call.
Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected. Consider the following code snippet:
Example: Incorrect usage of default function arguments
function makeyogurt($type = "acidophilus", $flavour)
{
return "Making a bowl of $type $flavour.\n";
}
echo makeyogurt("raspberry"); // won't work as expected
The above example will output:
Warning: Missing argument 2 in call to makeyogurt() in
/usr/local/etc/httpd/htdocs/phptest/functest.html on line 41
Making a bowl of raspberry .
Now, compare the above with this:
Example: Correct usage of default function arguments
function makeyogurt($flavour, $type = "acidophilus")
{
return "Making a bowl of $type $flavour.\n";
}
echo makeyogurt("raspberry"); // works as expected
The above example will output:
Making a bowl of acidophilus raspberry.
Note:
As of PHP 5, arguments that are passed by reference may have a default value.
Returning values
Values are returned by using the optional return statement. Any type may be returned, including arrays and objects. This causes the function to end its execution immediately and pass control back to the line from which it was called. See return for more information.
Note:
If the return is omitted the value NULL will be returned.
Example #1 Use of return
function square($num)
{
return $num * $num;
}
echo square(4); // outputs '16'.
A function can not return multiple values, but similar results can be obtained by returning an array.
Example: Returning an array to get multiple values
function small_numbers()
{
return array (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();
To return a reference from a function, use the reference operator & in both the function declaration and when assigning the returned value to a variable:
Example: Returning a reference from a function
function &returns_reference()
{
return $someref;
}
$newref =& returns_reference();
For more information on references, please check out References Explained.
Variable functions
PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.
Variable functions won’t work with language constructs such as echo, print, unset(), isset(), empty(), include, require and the like. Utilize wrapper functions to make use of any of these constructs as variable functions.
Example: Variable function example
function foo() {
echo "In foo()
\n";
}
function bar($arg = '')
{
echo "In bar(); argument was '$arg'.
\n";
}
// This is a wrapper function around echo
function echoit($string)
{
echo $string;
}
$func = 'foo';
$func(); // This calls foo()
$func = 'bar';
$func('test'); // This calls bar()
$func = 'echoit';
$func('test'); // This calls echoit()
Object methods can also be called with the variable functions syntax.
Example: Variable method example
class Foo
{
function Variable()
{
$name = 'Bar';
$this->$name(); // This calls the Bar() method
}
function Bar()
{
echo "This is Bar";
}
}
$foo = new Foo();
$funcname = "Variable";
$foo->$funcname(); // This calls $foo->Variable()
When calling static methods, the function call is stronger than the static property operator:
Example: Variable method example with static properties
class Foo
{
static $variable = 'static property';
static function Variable()
{
echo 'Method Variable called';
}
}
echo Foo::$variable; // This prints 'static property'. It does need a $variable in this scope.
$variable = "Variable";
Foo::$variable(); // This calls $foo->Variable() reading $variable in this scope.
Anonymous functions
Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses.
Example: Anonymous function example
echo preg_replace_callback('~-([a-z])~', function ($match) {
return strtoupper($match[1]);
}, 'hello-world');
// outputs helloWorld
Closures can also be used as the values of variables; PHP automatically converts such expressions into instances of the Closure internal class. Assigning a closure to a variable uses the same syntax as any other assignment, including the trailing semicolon:
Example #2 Anonymous function variable assignment example
$greet = function($name)
{
printf(“Hello %s\r\n”, $name);
};
$greet(‘World’);
$greet(‘PHP’);
Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct. Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from). See the following example:
Example: Closures and scoping
// A basic shopping cart which contains a list of added products
// and the quantity of each product. Includes a method which
// calculates the total price of the items in the cart using a
// closure as a callback.
class Cart
{
const PRICE_BUTTER = 1.00;
const PRICE_MILK = 3.00;
const PRICE_EGGS = 6.95;
protected $products = array();
public function add($product, $quantity)
{
$this->products[$product] = $quantity;
}
public function getQuantity($product)
{
return isset($this->products[$product]) ? $this->products[$product] :
FALSE;
}
public function getTotal($tax)
{
$total = 0.00;
$callback =
function ($quantity, $product) use ($tax, &$total)
{
$pricePerItem = constant(__CLASS__ . "::PRICE_" .
strtoupper($product));
$total += ($pricePerItem * $quantity) * ($tax + 1.0);
};
array_walk($this->products, $callback);
return round($total, 2);
}
}
$my_cart = new Cart;
// Add some items to the cart
$my_cart->add('butter', 1);
$my_cart->add('milk', 3);
$my_cart->add('eggs', 6);
// Print the total with a 5% sales tax.
print $my_cart->getTotal(0.05) . "\n";
// The result is 54.29
Changelog
5.4.0 : $this can be used in anonymous functions.
5.3.0 : Anonymous functions become available.