The example in the php documentation on Closure::bind
include static
on the anonymous function declaration. why? I can't find the difference if it is removed.
with:
class A { private static $sfoo = 1; } $cl1 = static function() { // notice the "static" return self::$sfoo; }; $bcl1 = Closure::bind($cl1, null, 'A'); echo $bcl1(); // output: 1
without:
class A { private static $sfoo = 1; } $cl1 = function() { return self::$sfoo; }; $bcl1 = Closure::bind($cl1, null, 'A'); echo $bcl1(); // output: 1
Closure are functions that may be stored in a variable : functions may have their name stored in a variable, though. Closure also have the ability to aggregate variables from the context of their creation, for future use. As such, $this is available in a closure that is created inside an object.
Anonymous functions, also known as closures , allow the creation of functions which have no specified name. They are most useful as the value of callable parameters, but they have many other uses. Anonymous functions are implemented using the Closure class.
The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.
A closure is a separate namespace, normally, you can not access variables defined outside of this namespace. There comes the use keyword: use allows you to access (use) the succeeding variables inside the closure. use is early binding. That means the variable values are COPIED upon DEFINING the closure.
found the difference: you can't bind static closures to object, only change the object scope.
class foo { } $cl = static function() { }; Closure::bind($cl, new foo); // PHP Warning: Cannot bind an instance to a static closure Closure::bind($cl, null, 'foo') // you can change the closure scope
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With