VGTech is a blog where the developers and devops of Norways most visited website share code and tricks of the trade… Read more



Are you brilliant? We're hiring. Read more

Comparing your privates in PHP

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.

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

Show code
<?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

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.

Developer at VG. @androa


0 comments

    Leave your comment