André Roaldseth
Written by André Roaldseth
Published 2014-03-14

Comparing your privates in PHP

While working with some code that should compare two different instances of the same class I discovered a “hidden” feature in PHP.

I was going to compare several private properties between to objects and started making a piece of code to perform the actual comparison using getters for the properties. I felt the approach sucked, and started looking into alternatives way to do this.

Entry image

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)!

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.

Written by André Roaldseth
Published 2014-03-14