When comparing objects, the PHP manual states:
When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.
When using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class.
At first I interpreted this as the properties has to be public. I wanted to enforce type on my properties so I did not want to make them public.
It turned out that the solution was hidden in plain sight, as object visibility in PHP is applied at a class-level, not a instance-level. That means that two object instances of the same class has access to each others private properties (and methods)!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | [code language="php"]<?php class A { private $prop; public function __construct($value) { $this->prop = $value; } } $a = new A(1); $b = new A(1); $c = new A(2); $d = new A("1"); var_dump($a == $b, $a == $c, $a == $d); // true, false, true [/code] |
This means that we use the comparison operator on two instances of the same class and do a comparison of ALL the properties, even the protected and private ones.
You can also use this to call private methods on other instances of the same class. Keeping this trick in mind can be really awesome for performing unit tests or implementing the Proxy pattern.