Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'self' in an anonymous callback?

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::toBeCalled();
        });
    }

}

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

like image 236
deceze Avatar asked Jul 10 '11 22:07

deceze


1 Answers

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
    */
like image 195
Kendall Hopkins Avatar answered Sep 28 '22 10:09

Kendall Hopkins