Anonymous Functions
Introduction
Anonymous recursive function is a type of recursion in which function does not explicitly call another function by name. In theory of computer science, anonymous recursion is significant, as anonymous recursion is type of recursion in which one can implement recursion without requiring named functions.
For example, to define a function that multiplies two numbers, you can do it as follows:
1 2 3 4 5 6 7 8 | <?php function multiply($x, $y) { return $x * $y; } //call the function multiply(10,20); |
In this example, the multiply() is a named function. And you can reuse it as many times as you want.
The following example defines an anonymous function that multiplies two numbers:
1 2 3 4 5 | <?php function ($x, $y) { return $x * $y; }; |
Since the function doesn’t have a name, you need to end it with a semicolon (;) because PHP treats it as an expression.
This anonymous function is not useful at all because you cannot use it like a named function.
To use an anonymous function, you need to assign it to a variable and call the function via the variable.
The following example assigns the anonymous function to the $multiply variable:
1 2 3 4 5 6 | <?php // ... $multiply = function ($x, $y) { return $x * $y; }; |
And this calls the anonymous function via the $multiply variable:
1 | echo $multiply(10, 20); |
Passing an anonymous function to another function
PHP has many built-in functions that accept a callback function, for example, the array_map() function.
The array_map() function accepts a callback function and an array. It applies the callback function to each element and includes the results in a new array.
The following example shows how to double each number in an array:
1 2 3 4 5 6 7 8 9 10 11 | <?php function double_it($element) { return $element * 2; } $list = [10, 20, 30]; $double_list = array_map(double_it, $list); print_r($double_list); |
How it works.
- First, define a named function called double_it to double a number.
- Second, define an array of integers.
- Third, call the array_map() function to double each element of the $list array.
- Finally, show the result array.
Output:
1 2 3 4 5 6 | Array ( [0] => 20 [1] => 40 [2] => 60 ) |
Scope of the anonymous function
By default, an anonymous function cannot access the variables from its parent scope.
Ex:
1 2 3 4 5 6 7 8 | <?php $message = 'Hi'; $say = function () { echo $message; }; $say(); |
PHP issued the following notice:
1 | PHP Notice: Undefined variable: message in ... |
In this example, the anonymous function attempts to access the $message variable from its parent scope. However, it could not. Therefore, PHP issued a notice.
To use the variables from the parent scope inside an anonymous function, you place the variables in the use construct as follows:
1 2 3 4 5 6 7 8 | <?php $message = 'Hi'; $say = function () use ($message) { echo $message; }; $say(); |
Now, it should work correctly.
Return an anonymous function from a function
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php function multiplier($x) { return function ($y) use ($x) { return $x * $y; }; } $double = multiplier(2); echo $double(100); // 200 $tripple = multiplier(3); echo $tripple(100); // 300 |
How it works.
- First, define a function called mutiplier that returns an anonymous function.
- Second, call the multiplier function and assign its returned value to the $double variable. Since the return value is a function, it can be invoked like a regular function ($double(2)).
- Third, call the multiplier function and assign its returned value to the $tripple variable. This time we passed 3 instead of 2.
Variable Functions
Introduction
Variable functions allow you to use a variable like a function. When you append parentheses () to a variable, PHP will look for the function whose name is the same as the value of the variable and execute it.
Ex:
1 2 3 4 5 6 7 | <?php $f = 'strlen'; echo $f('Hello'); //Output: //5 |
How it works.
- First, define a variable $f and initialize its value to the ‘strlen’ literal string.
- Second, use the $f as a function by passing the string ‘Hello’ to it.
More variable function examples
Using variable functions to call a method
The variable functions allow you to call the methods of an object. The syntax for calling a method using a variable function is as follows:
1 | $this->$variable($arguments) |
Notice that you need to prefix the variable name with the $ sign. In this case, you’ll have the $ sign before the this keyword and the variable name. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <?php class Str { private $s; public function __construct(string $s) { $this->s = $s; } public function lower() { return mb_strtolower($this->s, 'UTF-8'); } public function upper() { return mb_strtoupper($this->s, 'UTF-8'); } public function title() { return mb_convert_case($this->s, MB_CASE_TITLE, 'UTF-8'); } public function convert(string $format) { if (!in_array($format, ['lower', 'upper', 'title'])) { throw new Exception('The format is not supported.'); } return $this->$format(); } } |
How it works:
- First, define a
Str
class that has three methods for converting a string to lowercase, uppercase, and title case. - Second, define the
convert()
method that accepts a string. If theformat
argument is not one of the method names: lower, upper, and title, theconvert()
method will raise an exception. Otherwise, it’ll call the corresponding methodlower()
,upper()
ortitle()
.
The following shows how to use the convert()
method of the Str
class:
1 2 3 4 5 6 | <?php require_once 'Str.php'; $str = new Str('Hello there'); echo $str->convert('title'); |
Output:
1 | Hello There |
Using variable functions to call a static method
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php class Str { private $s; public function __construct(string $s) { $this->s = $s; } public function __toString() { return $this->s; } public static function compare(Str $s1, Str $s2) { return strcmp($s1, $s2); } } |
The Str
class has a constructor that accepts a string. It implements the toString()
method that converts the Str
instance to a string.
The Str
class has the compare()
static method that compares two instances of the Str
class. To call the compare()
static method using a variable function, you use the following:
1 2 3 4 5 6 | $str1 = new Str('Hi'); $str2 = new Str('Hi'); $action = 'compare'; echo Str::$action($str1, $str2); // 0 |