PHP Closure Binding a closure for one call

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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() {
    echo $this->property;
};

$myInstance = new MyClass('Hello world!');

$myClosure->call($myInstance); // Shows "Hello world!"

As opposed to the bindTo method, there is no scope to worry about. The scope used for this call is the same as the one used when accessing or invoking a property of $myInstance.



Got any PHP Question?