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->property;
};
class MyClass
{
public $property;
public function __construct($propertyValue)
{
$this->property = $propertyValue;
}
}
$myInstance = new MyClass('Hello world!');
$myBoundClosure = $myClosure->bindTo($myInstance);
$myBoundClosure(); // Shows "Hello world!"