7

Should an object's method be able to access a protected property of another object of the same class?

I'm coding in PHP, and I just discovered that an object's protected property is allowed to be accessed by a method of the same class even if not of the same object.

In the example, at first, you'll get "3" in the output - as function readOtherUser will have successfully accessed the value -, and after that a PHP fatal error will occur - as the main program will have failed accessing 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 the intended behaviour (and I'll have to relearn this concept… :)) (and are there references to the fact)? How is it done in other programming languages?

Thanks!

1
  • 1
    NB. Ruby's private behaves as described–a private method cannot be called on a different instance. Commented Jan 21, 2012 at 0:37

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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. 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.