Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite recursion in PHP echo statement

Why does this code cause an 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 normally

Is this because __toString() is returning an object? But that can't be possible because according to the docs

This method must return a string, as otherwise a fatal E_RECOVERABLE_ERROR level error is emitted. (ref)

Or does it just infinitely recurse within the __toString() method?

like image 880
Drakes Avatar asked Sep 23 '26 19:09

Drakes


1 Answers

echo new Foo();

creates a Foo and tries to echo it, to do so it casts the object to string invoking magic method __toString.

In that method, however, you invoke the static method Foo::newFoo, which returns a new object, which is again casted to string in __toString itself, which so gets called again.

So yes, here is infinite recursion.

To clarify:

public function __toString() {
    return "{${Foo::newFoo()}}";
}

is equivalent to

public function __toString() {
    $foo = Foo::newFoo();
    return "$foo"; // this is a cast as string, which invokes __toString() again.
}
like image 165
Matteo Tassinari Avatar answered Sep 25 '26 09:09

Matteo Tassinari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!