Less known fact about private and protected methods and properties Different objects can access each other private and protected members

Scroll this

This post assumes that you are familiar with object programming, encapsulation and you know why and how private/protected/public keywords are used.

But one simple fact is often missed. In PHP (and some other popular OO languages) visibility is class based, not object based! This means that your private/protected properties are not so private as you might thought since other instances (objects) of the same class can access it.

Different objects of the same class can access each other private and protected members!

Run this example code:

In this example object $fooB is accessing and changing private and protected properties of another object $fooA.

Output:

And this is not a bug, it is a feature. This is what PHP manual says about it:

Objects of the same type will have access to each others private and protected members even though they are not the same instances. This is because the implementation specific details are already known when inside those objects.

And the same applies to C++, Java and C# to name a few.

Lets run another test to see how class based visibility affects instances of the inherited classes:

Output:

This is to be expected. PHP interpreter applied class based visibility rules. Since inherited class can not access it’s parent private properties/method it is only logical that object of the inherited class can not access other object private members, when other object is instance of the parent class.

It can, however access protected members of the other object.

This works:

Output:

$barB object successfully accessed and changed protected property of another object $fooA.

References

Submit a comment