访问同一类的另一个对象的protected属性的方法 [英] Method accessing protected property of another object of the same class

查看:198
本文介绍了访问同一类的另一个对象的protected属性的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对象的方法是否能够访问同一类的另一个对象的受保护属性?



我在PHP中编码,我刚刚发现对象的protected属性允许通过相同类的方法访问,即使不是同一个对象。



在示例中,首先, 3在输出中 - 作为函数readOtherUser将成功访问该值 - ,然后将发生PHP致命错误 - 因为主程序将无法访问相同的值。

 <?php 

class user
{
protected $ property = 3;

public function readOtherUser()
{
$ otherUser = new user();
print $ otherUser-> property;
}
}

$ user = new user();

$ user-> readOtherUser();
print $ user-> property;这是一个PHP错误,或者是它的预期行为(和我'我必须重新学习这个概念... :))(和有参考的事实)?在其他编程语言中如何实现?



谢谢!

解决方案

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



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.

这篇关于访问同一类的另一个对象的protected属性的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆