Method for accessing a protected property of another object of the same class

Should an object method have access to a protected property of another object of the same class?

I am coding in PHP, and I just found that access to an object-protected property is allowed using a method of the same class, even if it is not of the same object.

In this example, you first get β€œ3” in the output - because the readOtherUser function will successfully access the value - and after that a fatal PHP error will occur - because the main program will have failed access with the same value.

<?php class user { protected $property = 3; public function readOtherUser () { $otherUser = new user (); print $otherUser->property; } } $user = new user (); $user->readOtherUser (); print $user->property; ?> 

Is this a PHP bug or is it supposed behavior (and I will have to retrain this concept ... :)) (and are there any links to this fact)? How is this done in other programming languages?

Thanks!

+6
visibility object php class instance
source share
2 answers

It is intended. Access to private members of the same class is possible. So think of modifiers to be cool modifiers, not object modifiers.

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

+6
source share

It was meant to be behavior. A protected variable or function means that it can be accessed by the same class or any class that inherits from this class. A protected method can only be called from a class, for example. you cannot call it this way:

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

This will give you an error message. However, from within a specific "MyClass" class, you can fully invoke a protected function.

The same applies to 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. 
+2
source share

All Articles