PHPverse 2025

Voting

: eight plus one?
(Example: nine)

The Note You're Voting On

Hayley Watson
16 years ago
This has already been mentioned (see jazfresh at hotmail.com's note), but here it is again in more detail because for objects the difference between == and === is significant.

Loose equality (==) over objects is recursive: if the properties of the two objects being compared are themselves objects, then those properties will also be compared using ==.

<?php
class Link
{
public
$link; function __construct($link) { $this->link = $link; }
}
class
Leaf
{
public
$leaf; function __construct($leaf) { $this->leaf = $leaf; }
}

$leaf1 = new Leaf(42);
$leaf2 = new Leaf(42);

$link1 = new Link($leaf1);
$link2 = new Link($leaf2);

echo
"Comparing Leaf object equivalence: is \$leaf1==\$leaf2? ", ($leaf1 == $leaf2 ? "Yes" : "No"), "\n";
echo
"Comparing Leaf object identity: is \$leaf1===\$leaf2? ", ($leaf1 === $leaf2 ? "Yes" : "No"), "\n";
echo
"\n";
echo
"Comparing Link object equivalence: is \$link1==\$link2? ",($link1 == $link2 ? "Yes" : "No"), "\n";
echo
"Comparing Link object identity: is \$link1===\$link2? ", ($link1 === $link2 ? "Yes" : "No"), "\n";
?>

Even though $link1 and $link2 contain different Leaf objects, they are still equivalent because the Leaf objects are themselves equivalent.

The practical upshot is that using "==" when "===" would be more appropriate can result in a severe performance penalty, especially if the objects are large and/or complex. In fact, if there are any circular relationships involved between the objects or (recursively) any of their properties, then a fatal error can result because of the implied infinite loop.

<?php
class Foo { public $foo; }
$t = new Foo; $t->foo = $t;
$g = new Foo; $g->foo = $g;

echo
"Strict identity: ", ($t===$g ? "True" : "False"),"\n";
echo
"Loose equivalence: ", ($t==$g ? "True" : "False"), "\n";
?>

So preference should be given to comparing objects with "===" rather than "=="; if two distinct objects are to be compared for equivalence, try to do so by examining suitable individual properties. (Maybe PHP could get a magic "__equals" method that gets used to evaluate "=="? :) )

<< Back to user notes page

To Top