Closing php: why is “static” in an anonymous function declaration when bound to a static class?

An example in the php documentation on Closure::bind includes static in the declaration of an anonymous function. What for? I can not find the difference if it is deleted.

with

 class A { private static $sfoo = 1; } $cl1 = static function() { return self::$sfoo; }; // notice the "static" $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 
+11
source share
3 answers

As you noticed, this does not really matter, although it may seem like an error if E_STRICT included in error_reporting . (Update: no, it is not)

This is similar to using the static in a class method. You don’t have to if you don’t reference $this inside the method (although this violates strict standards).

I suppose PHP can work, you mean Closure to access A statically due to the null second argument of bind()

+4
source

found the difference: you cannot bind static closures to an object, but only change the scope of the object.

 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 
+21
source

Static closures, like any other static method, cannot access $this .

Like any other method, a non-static closure that does not have access to $this usually works in a static context.

However, static closures, like any other static method, have a slight performance advantage over non-static closures, so in the interest of microcode optimization, I personally recommend declaring any closures that do not require access to $this as static.

0
source

Source: https://habr.com/ru/post/957805/


All Articles