Monday, August 2, 2010

Do you really know everything about private and public?

I've seen for a long time that usual questions about access modificators in OOP limited on enumeration (public, protected, private) and what can be enherited. However many developers (including PHP and C++ ) don't even think about how this modifiers influent on object instances presuming that they behave exactly the same as classes. But this is not true.

For example: We have class A. This class has private property $pr. Also this class has method that takes two arguments: Some string and another (second) instance of class A. This method will change $pr property of given (second) instance of class A. How comiler/translator will behave?

Let's try:
What this code will output? The most of people will say "Of course fatal error. $objOne tryes to change private property of another object". But in fact we should always remember that: access modifiers (including private) restrict access for another classes, not for objects (instance). Code will run and user will see "passed" because all job is doing in one class. This is OOP fundamental, that's why this behavoiur should be same in both PHP and C++ (and other OOP languages).