I was given a question to answer without executing.
class Foo {
public $x;
}
$a = new Foo();
$b = new Foo();
$a->x = $b;
$b->x = $a;
print_r($a == $b);
I thought this should print 1 but when i executed it gave a fatal error.
Fatal error: Nesting level too deep - recursive dependency? on line 13
Can anyone explain why i am getting this error ?
Because of the way PHP compares objects.
When you compare objects with
==, PHP will look at each property of each object (and nested objects, in case some properties contain other objects), and compare them. The objects would be considered equal if all properties are equal.In this specific case, you’re placing the objects within each others’ properties, causing the comparison engine to loop (
$a->b->a->b->a->b->...), which throws an error.