Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method accessing protected property of another object of the same class

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!

like image 340
Jānis Elmeris Avatar asked Nov 22 '09 13:11

Jānis Elmeris


2 Answers

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.

like image 177
Ikke Avatar answered Oct 05 '22 23:10

Ikke


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.
like image 32
TheGrandWazoo Avatar answered Oct 06 '22 00:10

TheGrandWazoo