Access private properties of different object of the same class

Have a look at the following code:

class A
{
    private $var = 17;

    public function accessOtherPrivate(A $a)
    {
        echo $a->var;
    }

}

$a = new A();
$b = new A();
$b->accessOtherPrivate($a);

The code above works just fine, you can access private properties of different object – as long as you’re the same class. PHP manual confirms the behaviour:

Members declared as private may only be accessed by the class that defines the member.

Java has the same behaviour.

  1. ah yes! I came across this (in enovation actually) and it felt very wtf to me at the time. but as you say, it’s documented, so I guess it’s a ‘feature’ :)

    You can leverage this with inheritance as well, if you create class B inheriting from A, then this works when calling methods on B inherited from A. Nothing unexpected there… nor the fact that calling A::$var in an explicitly defined method in B causes a fatal error.

    But you can read A::$var from explicitly defined methods in a separate instance of B. Which also makes sense I guess, at least within the logic of this ‘feature’!

    The main thing that interested me is… useful applications! I’m sure there are some. Any thoughts?

    PS: this reminds me of a much bigger WTF I stumbled across some years ago which I must dig out!

  2. I can’t edit my post… what I meant to say above of course, was:

    But you can read A::$var from explicitly defined methods in a separate instance of B, if it’s protected. Which also makes sense I guess, at least within the logic of this ‘feature’!

  3. Regarding the other WTF. The docs now kinda clarify it a bit, but it still seems weird to me. Maybe a little less, now that I think of it again. But it’s still sorta interesting.

    Basically:

    * If you define a const in an interface, the implementing class cannot override it. Which seems sensible.

    * If you define a const in a class, an inheriting child class can override the parent const.

    Therefore, one scenario is that the top-level class implementing a specific interface cannot override its constants, but a child of the top-level class can.

    https://gist.github.com/darraghenright/6733690

    Hmm.. I guess it makes sense actually :)

Leave a Comment


*


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">