Tom Jenkinson
Tom Jenkinson

Reputation: 1470

Accessing 'parent' in PHP Anonymous Function (and possible bug)

Does anyone know how to get access to a function on the parent class from inside an anonymous function defined in a class? Is this actually meant to be possible? I would presume not and that I would have to get a reference to the parent class into the anonymous function with the "use" keyword somehow.

However, if I run the following code on a local apache server running on windows with version 5.4.12 of php it works and b and a are outputted.

If I run it on a apache server running on linux with php version 5.3.10-1ubuntu3.11 with Suhosin-Patch (cli) I get the error Fatal error: Cannot access parent:: when no class scope is active on line 17.

echo("PHP version: ".phpversion()."<br /><br />");

class A {

    public function fn() {
        echo("in A");
    }   

}

class B extends A {

    public function fn() {
        echo("in B");

        $anonFn = function() {
            parent::fn(); // this causes the error (sometimes)
        };
        $anonFn();
    }

}


$b = new B();
$b->fn();

If you paste the above code into http://writecodeonline.com/php/ the error still occurs.

So my questions are,

Thanks!

Upvotes: 1

Views: 979

Answers (1)

Barmar
Barmar

Reputation: 781761

PHP 5.4 includes class scope in closures, PHP 5.3 doesn't.

Upvotes: 3

Related Questions