Skip to content

PHP 7 – Closure

Last updated on December 13, 2015

Another cool new future in PHP 7 allows to bind a closure to a specific object on run-time with the addition of Closure->call() function.

This method takes the object as it’s first argument, followed by any arguments to pass into the closure.

Syntax

mixed Closure::call(object $to[, mixed ...$parameters])

Example with PHP7:

class HelloWorld {
     private $greeting = "Hello";
}
 
$closure = function($whom) { echo $this->greeting . ' ' . $whom; }
 
$obj = new HelloWorld();
$closure->call($obj, 'World'); // Hello World

Before PHP7 we use to do something similar to below example with bindTo() method and which allow creating new closures that have $this bound to a specific method. However, it has not been possible to bind at call time and you must instead create a temporary new closure.

class HelloWorld {
     private $greeting = "Hello";
}
 
$closure = function($whom) { echo $this->greeting . ' ' . $whom; };
$closure = $closure->bindTo(new HelloWorld , 'HelloWorld');  // intermediate closure
$closure(' World'); // Hello World
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments