Method accessing protected property of another object of the same class

跟風遠走 提交于 2019-12-05 04:46:06

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.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!