开发者

Using 'self' in an anonymous callback?

开发者 https://www.devze.com 2023-03-19 10:38 出处:网络
Take a contrived example where I want to call a protected static method from another context through a callback function:

Take a contrived example where I want to call a protected static method from another context through a callback function:

class Foo {

    protected static function toBeCalled() { }

    public static function bar() {
        functionThatAcceptsACallback(function () {
            self::toBeCall开发者_Python百科ed();
        });
    }

}

Is this possible in PHP 5.3? I couldn't find a way to make it work...


It's not possible, but it will be in 5.4 along with support for $this in a closure.

Added closure $this support back. (Stas)

Reference

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
    */
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号