Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Comparing Objects with == and ===

When comparing objects , = = and = = = may not work quite as you expect them to. If you were comparing two integers of the same value (e.g., 5), then = = and = = = would both return true; however, with objects, = = compares the objects' contents and = = = compares the objects' handles.

There is a difference there, and it's crucial: if you create an object and clone it, its clone will have exactly the same values. It will, therefore, return true for = = as the two objects are the same in terms of their values. However, if you use = = , you will get false back, because it compares the handles of the objects and finds them to be different. This code example demonstrates this:

    class Employee { }

    $Bob = new Employee();
    $Joe = clone $Bob;

    print (int)($Bob == $Joe) . "\n";
    print (int)($Joe === $Joe) . "\n";

That will output a 1, then a 0. Apart from basic comparison differences, this also matters because versions of PHP at 5.0.2 and earlier can encounter problems when doing a = = comparison in very specific objects, like this:

    class Employee {
            public function _ _construct() {
                    $this->myself = $this;
            }
    }

    $Bob = new Employee();
    $Joe = clone $Bob;

    print (int)($Bob == $Joe) . "\n";
    print (int)($Bob === $Joe) . "\n";

There is a class that puts a reference to itself in the $myself property on construction. Naturally, this is a silly thing to do, but the example is simplified—in a real scenario, it might store a reference to another object that has a reference back ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page