Chapter 8. Closure Enhancements
Closures have been around since PHP 5.3, and with PHP 5.4, the ability to access an early-bound $this within them was added. In addition to this, the Closure class went from being an implementation detail to being probably the easiest way to break PHP’s object model.
PHP 7.0 makes this even easier.
Bind Closure On Call
With the addition of $this, Closure gained two methods, the instance method Closure->bindTo() and the static method Closure::bind().
Both of these functions do the same thing, but the first is called on the closure instance itself, while the static version must be passed the closure itself as the first argument. They both then take two arguments: the first is an object that $this will then point to, and the second is the scope from which to access $this.
This second one is important, because it means that you can change the scope to that of another class allowing you to call its private and protected methods and properties.
Both of the functions will then return a clone of the closure with the new $this and scope, rather than modifying the original.
The “Closure::call” RFC gives us an easier way to achieve the most common case, without needing to clone the object.
With PHP 7.0, the Closure class has a new instance method, Closure->call(), which takes an object as its first argument, to which $this is bound, and to which the scope is set, and then it calls the closure passing through any additional arguments passed to Closure->call() ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access