Infinite recursion in PHP echo statement -
why code cause infinite recursion?
class foo { public static function newfoo() { return new foo(); } public function __tostring() { return "{${foo::newfoo()}}"; } } echo new foo(); // infinite recursion new foo(); // finishes is because __tostring() returning object? can't possible because according docs
this method must return string, otherwise fatal e_recoverable_error level error emitted. (ref)
or infinitely recurse within __tostring() method?
echo new foo(); creates foo , tries echo it, casts object string invoking magic method __tostring.
in method, however, invoke static method foo::newfoo, returns new object, again casted string in __tostring itself, gets called again.
so yes, here infinite recursion.
to clarify:
public function __tostring() { return "{${foo::newfoo()}}"; } is equivalent to
public function __tostring() { $foo = foo::newfoo(); return "$foo"; // cast string, invokes __tostring() again. }
Comments
Post a Comment