PHP
The Closure class
Learn that anonymous functions are instances of the Closure class.
Anonymous functions and the Closure class
In PHP, a function without a name is called an anonymous function. It is created with the function () { return 'hi'; } syntax and can be assigned to a variable.
Every anonymous function is an instance of PHP's Closure class. So $fn instanceof Closure is true. The word 'Closure' suggests the function can encapsulate the scope where it was defined.
You assign the unnamed function to a variable and call it later with $fn(5). This lets you carry functions around like data.
Assign a closure to a variable and call it
You can assign a closure to a variable like $fn and call it later. The line $fn = function ($x) { return $x + 1; }; defines the closure; the trailing semicolon is required.
After the definition, the call $fn(5) runs the closure and returns the result. Just like regular functions, it can take parameters and return values.
You can also add types: $fn = function (int $x): int { return $x + 1; }; — this adds safety.
Exercise A closure that doubles its input
Define a closure named $double: it takes $x and returns $x * 2. Then call $double(8) and print the result on a new line.
Show example solution
Assign $double = function ($x) { return $x * 2; }. Then write echo $double(8) . "\n";.
Example solution:
<?php
// Write a closure that doubles and call it
$double = function ($x) {
return $x * 2;
};
echo $double(8) . "\n";
Test yourself
-
Which class is an anonymous function an instance of?
- stdClass
- Closure
- Function
- Lambda
Show answer
Closure — Correct. Every anonymous function is an instance of the Closure class in PHP.
-
Complete the closure definition
<?php
$fn = ____ ($n) {
return ['val' => $n * 2];
};
print_r($fn(5));
Show answer
<?php
$fn = function ($n) {
return ['val' => $n * 2];
};
print_r($fn(5));
-
Match the closure concepts
- function () {}
- Anonymous function
- Closure
- Class of anonymous functions
- $fn(5)
- Calls the closure
- instanceof Closure
- Checks if it is a Closure
Next lesson: Capturing variables with use