Functions User-defined functions A function may be defined using syntax such as the following: Pseudo code to demonstrate function uses ]]> 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_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$. &tip.userlandnaming; 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. Conditional functions ]]> Functions within functions ]]> 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. Function names are case-insensitive for the ASCII characters A to Z, 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. Recursive functions ]]> Recursive function/method calls with over 100-200 recursion levels can smash the stack and cause a termination of the current script. Especially, infinite recursion is considered a programming error. 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 and Named Arguments are also supported. Passing arrays to functions ]]> As of PHP 8.0.0, the list of function arguments may include a trailing comma, which will be ignored. That is particularly useful in cases where the list of arguments is long or contains long variable names, making it convenient to list arguments vertically. Function Argument List with trailing Comma ]]> As of PHP 8.0.0, passing mandatory arguments after optional arguments is deprecated. This can generally be resolved by dropping the default value. One exception to this rule are arguments of the form Type $param = null, where the &null; default makes the type implicitly nullable. This usage remains allowed, though it is recommended to use an explicit nullable type instead. Passing optional arguments after mandatory arguments ]]> Passing arguments 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: Passing function parameters by reference ]]> It is an error to pass a value as argument which is supposed to be passed by reference. Default argument values A function may define C++-style default values for scalar arguments as follows: Use of default parameters in functions ]]> &example.outputs; PHP also allows the use of arrays and the special type &null; as default values, for example: Using non-scalar types as default values ]]> 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: Incorrect usage of default function arguments ]]> &example.outputs; Now, compare the above with this: Correct usage of default function arguments ]]> &example.outputs; Arguments that are passed by reference may have a default value. Variable-length argument lists PHP has support for variable-length argument lists in user-defined functions by using the ... token. It is also possible to achieve variable-length arguments by using func_num_args, func_get_arg, and func_get_args functions. This technique is not recommended as it was used prior to the introduction of the ... token. Argument lists may include the ... token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array; for example: Using <literal>...</literal> to access variable arguments ]]> &example.outputs; ... can also be used when calling functions to unpack an array or Traversable variable or literal into the argument list: Using <literal>...</literal> to provide arguments ]]> &example.outputs; You may specify normal positional arguments before the ... token. In this case, only the trailing arguments that don't match a positional argument will be added to the array generated by .... It is also possible to add a type declaration before the ... token. If this is present, then all arguments captured by ... must be objects of the hinted class. Type declared variable arguments $unit; } return $time; } $a = new DateInterval('P1D'); $b = new DateInterval('P2D'); echo total_intervals('d', $a, $b).' days'; // This will fail, since null isn't a DateInterval object. echo total_intervals('d', null); ?> ]]> &example.outputs; Finally, variable arguments can also be passed by reference by prefixing the ... with an ampersand (&). Older versions of PHP No special syntax is required to note that a function is variadic; however access to the function's arguments must use func_num_args, func_get_arg and func_get_args. The first example above would be implemented as follows in old versions of PHP: Accessing variable arguments in old PHP versions ]]> &example.outputs; Named Arguments PHP 8.0.0 introduced named arguments as an extension of the existing positional parameters. Named arguments allow passing arguments to a function based on the parameter name, rather than the parameter position. This makes the meaning of the argument self-documenting, makes the arguments order-independent and allows skipping default values arbitrarily. Named arguments are passed by prefixing the value with the parameter name followed by a colon. Using reserved keywords as parameter names is allowed. The parameter name must be an identifier, specifying dynamically is not allowed. Named argument syntax ]]> Positional arguments versus named arguments ]]> The order in which the named arguments are passed does not matter. Same example as above with a different order of parameters ]]> Named arguments can be combined with positional arguments. In this case, the named arguments must come after the positional arguments. It is also possible to specify only some of the optional arguments of a function, regardless of their order. Combining named arguments with positional arguments ]]> Passing the same parameter multiple times results in an Error exception. Error exception when passing the same parameter multiple times ]]> 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. If the return is omitted the value &null; will be returned. Use of return Use of <function>return</function> ]]> A function can not return multiple values, but similar results can be obtained by returning an array. Returning an array to get multiple values ]]> 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: Returning a reference from a function ]]> 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. Variable function example \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. Variable method example $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: Variable method example with static properties Variable() reading $variable in this scope. ?> ]]> Complex callables ]]> &reftitle.seealso; is_callable call_user_func function_exists variable variables
Internal (built-in) functions PHP comes standard with many functions and constructs. There are also functions that require specific PHP extensions compiled in, otherwise fatal "undefined function" errors will appear. For example, to use image functions such as imagecreatetruecolor, PHP must be compiled with GD support. Or, to use mysqli_connect, PHP must be compiled with MySQLi support. There are many core functions that are included in every version of PHP, such as the string and variable functions. A call to phpinfo or get_loaded_extensions will show which extensions are loaded into PHP. Also note that many extensions are enabled by default and that the PHP manual is split up by extension. See the configuration, installation, and individual extension chapters, for information on how to set up PHP. Reading and understanding a function's prototype is explained within the manual section titled how to read a function definition. It's important to realize what a function returns or if a function works directly on a passed in value. For example, str_replace will return the modified string while usort works on the actual passed in variable itself. Each manual page also has specific information for each function like information on function parameters, behavior changes, return values for both success and failure, and availability information. Knowing these important (yet often subtle) differences is crucial for writing correct PHP code. If the parameters given to a function are not what it expects, such as passing an array where a string is expected, the return value of the function is undefined. In this case it will likely return &null; but this is just a convention, and cannot be relied upon. &reftitle.seealso; function_exists the function reference get_extension_funcs dl 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 callable parameters, but they have many other uses. Anonymous functions are implemented using the Closure class. Anonymous function example ]]> 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: Anonymous function variable assignment example ]]> Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct. As of PHP 7.1, these variables must not include &link.superglobals;, $this, or variables with the same name as a parameter. Inheriting variables from the parent scope ]]> &example.outputs.similar; As of PHP 8.0.0, the list of scope-inherited variables may include a trailing comma, which will be ignored. 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: Closures and scoping 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 ?> ]]> Automatic binding of <literal>$this</literal> testing(); $function(); ?> ]]> &example.outputs; When declared in the context of a class, the current class is automatically bound to it, making $this available inside of the function's scope. If this automatic binding of the current class is not wanted, then static anonymous functions may be used instead. Static anonymous functions Anonymous functions may be declared statically. This prevents them from having the current class automatically bound to them. Objects may also not be bound to them at runtime. Attempting to use <literal>$this</literal> inside a static anonymous function ]]> &example.outputs; Attempting to bind an object to a static anonymous function bindTo(new StdClass); $func(); ?> ]]> &example.outputs; &reftitle.changelog; &Version; &Description; 7.1.0 Anonymous functions may not close over &link.superglobals;, $this, or any variable with the same name as a parameter. &reftitle.notes; It is possible to use func_num_args, func_get_arg, and func_get_args from within a closure. Arrow Functions Arrow functions were introduced in PHP 7.4 as a more concise syntax for anonymous functions. Both anonymous functions and arrow functions are implemented using the Closure class. Arrow functions have the basic form fn (argument_list) => expr. Arrow functions support the same features as anonymous functions, except that using variables from the parent scope is always automatic. When a variable used in the expression is defined in the parent scope it will be implicitly captured by-value. In the following example, the functions $fn1 and $fn2 behave the same way. Arrow functions capture variables by value automatically $x + $y; // equivalent to using $y by value: $fn2 = function ($x) use ($y) { return $x + $y; }; var_export($fn1(3)); ?> ]]> &example.outputs; This also works if the arrow functions are nested: Arrow functions capture variables by value automatically, even when nested fn($y) => $x * $y + $z; // Outputs 51 var_export($fn(5)(10)); ?> ]]> Similarly to anonymous functions, the arrow function syntax allows arbitrary function signatures, including parameter and return types, default values, variadics, as well as by-reference passing and returning. All of the following are valid examples of arrow functions: Examples of arrow functions $x; static fn(): int => $x; fn($x = 42) => $x; fn(&$x) => $x; fn&($x) => $x; fn($x, ...$rest) => $rest; ?> ]]> Arrow functions use by-value variable binding. This is roughly equivalent to performing a use($x) for every variable $x used inside the arrow function. A by-value binding means that it is not possible to modify any values from the outer scope. Anonymous functions can be used instead for by-ref bindings. Values from the outer scope cannot be modified by arrow functions $x++; // Has no effect $fn(); var_export($x); // Outputs 1 ?> ]]> &reftitle.changelog; &Version; &Description; 7.4.0 Arrow functions became available. &reftitle.notes; It is possible to use func_num_args, func_get_arg, and func_get_args from within an arrow function.