且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

访问同一类的另一个对象的protected属性的方法

更新时间:2023-11-27 15:35:46

这是打算。甚至可以访问同一类的私有成员。因此,想想修饰符是类明明的修饰符,而不是对象修饰符。



PHP不是唯一具有此功能的语言。例如Java也有这个。


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!

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.