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!
$thisandparent::.$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!