Using "self" in an anonymous callback?

Take a far-fetched example where I want to call the protected static method from another context via a callback function:

 class Foo { protected static function toBeCalled() { } public static function bar() { functionThatAcceptsACallback(function () { self::toBeCalled(); }); } } 

Is this possible in PHP 5.3? I could not find a way to make it work ...

+6
source share
1 answer

This is not possible , but it will be in 5.4 along with support for $this in closing.

Added closing $ of this support back. (Stas)

Link

Edit

This works in 5.4alpha1.

  class A { private function y() { print "y".PHP_EOL; } static private function z() { print "z".PHP_EOL; } function x() { return function() { $this->y(); self::z(); }; } } $class = new A(); $closure = $class->x(); $closure(); /* Output: y z */ 
+8
source

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


All Articles