Functions in PHP are similar to those in other programming languages like Java. And some new features are introduced such as arrow functions (Since PHP 7.4). Here we will introduce PHP function definition, arguments, returning values, variable functions, anonymous functions as well as arrow functions.
Function definition
A function definition in PHP looks like:
function foo( $arg1, $arg2, /* ..., */ $argn ) {
return 'I am a function.';
}
// or with type declarations (argument, returning value)
// argument type declaration
function sum( float $a, float $b ) {
return $a + $b;
}
// returning value type declaration
function sum( $a, $b ): float {
return $a + $b;
}
// type declaration of argument and returning value
function sum( float $a, float $b ): float {
return $a + $b;
}
// nullable returning type decalration
// It return a string or null.
function get_name(): ?string {
if ( isset($_GET['name'] ) ) {
return $_GET['name'];
} else {
return null;
}
}
A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.
Function arguments
Except the normal arguments, PHP function arguments support reference arguments, default argument values and variable-length arguments.
In PHP, a function is type of callable, so it is able to pass a function as an argument that you’ve seen in PHP Type.
- In variable functions part, you will see how to pass a function as an argument.
-
In anonymous functions part, you will see how to pass an anonymous function (callback) as an argument.
Reference arguments
Different from function arguments passed by value (if the value of the argument within the function is changed, it does not get changed outside of the function), arguments passed by reference allow a function to modify its arguments.
function append_extension( &$str )
{
$str .= '.csv';
}
$name = 'test';
append_extension( $name );
echo $name; // test.csv
Default argument values
The type of default argument value in PHP can be literal value or a complex
# A string as a default argument value.
function append_extension( $str, $ext = '.csv' )
{
return $str .= $ext;
}
echo append_extension( 'data' ); // data.csv
echo append_extension( '.json' ); // data.json
# An array as a default argument value.
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");
Note:
The default value must be a constant expression, not a variable.
Returning values
Use return statement to return values. In PHP, if there are multiple values needed to be return, return an array and use a list to receive them when calling the function. And you can return a reference variable.
Note:
If the return is omitted the value NULL will be returned.
Return multiple values
A function can not return multiple values, but you can return an array to achieve the similar results.
Example
// Return multiple values as an array
function split_email ( $email ) {
$pos = strpos( $email, '@' );
if ( $pos !== false ) {
return array( substr( $email, 0, $pos), substr( $email, $pos + 1 ) );
} else {
return array( $email, null );
}
}
list( $user, $domain ) = split_email( 'john@test.com' );
echo $user; // john
echo $domain; // test.com
The list
allows you to just get some of the elements.
// Just get the first element
list( $user ) = split_email( 'lily@test.com' );
echo $user; // lily
Return a reference variable
Example
Variable functions
Variable functions are those functions that are used as variables with type of callable, therefore they are more like function variables.
Examples
function func1() {
echo 'func1';
}
$f = 'func1';
$f(); // call func1()
function func2( $str = '') {
echo $str;
}
$f = 'func2';
$f(); // cal func2()
// class functions as variables
class MyClass {
function myMethod() {
echo 'I am myMethod';
}
static function myStaticMethod() {
echo 'I am myStaticMethod!';
}
}
$f = array( 'MyClass', 'myMethod' );
$f(); // prints "bar"
$f = array( new MyClass, 'myMethod' );
$f(); // prints "baz"
$f = "Foo::bar";
$f(); // prints "bar" as of PHP 7.0.0; prior, it raised a fatal error
Anonymous functions
Anonymous functions are often being used as callback functions. In PHP, they are implemented using Closure class.
Examples
# Example 1: Pass an anonymous function as a parameter
# array_map() accepts a function and an array as its parameters. It calls the function for each value in the array and return an new array with each result as its element.
$new_numbers = array_map(function( $v ){ return $v * 2; }, [1, 2]);
# Example 2: Return an anomymous function
function get_handler( $param ) {
return var_dump( $param );
}
# Example 3: Assign an anonymous function to an variable
$say_hello = function ( $name ) {
printf( "Hello %s!%s", $name, PHP_EOL );
}
$say_hello( 'PHP' );
# Example 4: An anonymous function inside a function of a class
class Test
{
public function testing()
{
return function() {
var_dump($this); // It have access to $this
};
}
}
Arrow functions
Arrow functions were introduced in PHP 7.4. They are like anonymous functions, but more handy. A main difference is arrow functions use variables from the parent scope automatically however anonymous functions do not. In fact, both of them are implemented by using the Closure class.
Like other languages, array functions in PHP have the basic form:
fn ( args ) => expr;
Examples
# Example 1
$a = 1;
$fn = fn($x) => $x + $a;
echo $fn( 2 ); // Outputs 3
# Example 2: Values from the outer scope cannot be modified by arrow functions
$a = 1;
$fn = fn() => $x++; // Has no effect
$fn();
echo $a; // Outputs 1
# Example 3: Nested arrow function
$z = 1;
$fn = fn( $x ) => fn( $y ) => $x * $y + $z;
echo $fn( 5 )( 10 ); // Outputs 51