Tutorial by Examples

A closure is the PHP equivalent of an anonymous function, eg. a function that does not have a name. Even if that is technically not correct, the behavior of a closure remains the same as a function's, with a few extra features. A closure is nothing but an object of the Closure class which is create...
It is possible, inside a closure, to use an external variable with the special keyword use. For instance: <?php $quantity = 1; $calculator = function($number) use($quantity) { return $number + $quantity; }; var_dump($calculator(2)); // Shows "3" You can go further by ...
As seen previously, a closure is nothing but an instance of the Closure class, and different methods can be invoked on them. One of them is bindTo, which, given a closure, will return a new one that is bound to a given object. For example: <?php $myClosure = function() { echo $this->p...
Let's consider this example: <?php $myClosure = function() { echo $this->property; }; class MyClass { public $property; public function __construct($propertyValue) { $this->property = $propertyValue; } } $myInstance = new MyClass('Hello world...
Since PHP7, it is possible to bind a closure just for one call, thanks to the call method. For instance: <?php class MyClass { private $property; public function __construct($propertyValue) { $this->property = $propertyValue; } } $myClosure = function() ...
In general, an observer is a class with a specific method being called when an action on the observed object occurs. In certain situations, closures can be enough to implement the observer design pattern. Here is a detailed example of such an implementation. Let's first declare a class whose purpos...

Page 1 of 1