Method accessing protected property of another object of the same class Method accessing protected property of another object of the same class php php

Method accessing protected property of another object of the same class


This is intended. It's even possible to access the private members of the same class. So think of the modifiers to be class wise modifiers, not objectwise modifiers.

PHP is not the only language that has this feature. Java for example has this too.


It's intended behavior. A protected variable or function means that it can be accessed by the same class or any class that inherits from that class. A protected method may only be called from within the class, e.g. you cannot call it like this:

$object = new MyClass();$object->myProtectedFunction();

This will give you an error. However, from within the defined class 'MyClass', you can perfectly call the protected function.

Same applies for variabeles. Summarized:

use PROTECTED on variables and functions when: 1. outside-code SHOULD NOT access this property or function. 2. extending classes SHOULD inherit this property or function.