1

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,

  • should this work or not, do I need to file a php bug report?
  • If it should always throw the error it is throwing, how do I actually get a reference to 'parent' in an anonymous function?

Thanks!

5
  • 1
    I think this is one of the enhancements in PHP 5.4 -- class scope is saved in closures, so you can use $this and parent::. Commented May 23, 2014 at 10:38
  • See this related question: stackoverflow.com/questions/23819597/… Commented May 23, 2014 at 10:39
  • 1
    php.net/manual/en/functions.anonymous.php Commented May 23, 2014 at 10:41
  • That would make sense. It's just it doesn't seem to mention in any of those explicitly that it is $this and parent::, only $this. In the changelog on the anonymous functions page they say $this can be used in anonymous functions. Maybe this should be changed to include 'and parent::' as well? Makes sense though, I'll get php updated. Thanks! Commented May 23, 2014 at 10:46
  • @Barmar if you post it as an answer I'll accept it. I presume that's the reason. Commented May 23, 2014 at 16:00

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.