简体   繁体   English

PHP类的私有属性和方法

[英]PHP class private property and method

Noticed something about PHP's classes and I don't know if it's a bug or why it works, this is the code: 注意到PHP的类,我不知道它是一个错误或它为什么工作,这是代码:

<?php
class A {
    private $prop = 'value';

    public function fun()
    {
        $obj = new A;
        $obj->echoProp();
    }

    private function echoProp()
    {
        echo 'Prop has value: '.$this->prop;
    }
}

$obj = new A;
$obj->fun();

And the result isn't an error as I was expecting since I'm calling a private method (tested on PHP 5.3.10-1ubuntu3.7 with Suhosin-Patch). 结果不是我所期待的错误,因为我正在调用一个私有方法(在PHP 5.3.10-1ubuntu3.7上用Suhosin-Patch测试)。 The result is "Prop has value: value" 结果是“道具有价值:价值”

只要你在课堂上,就可以在任何实例上调用你的类的私有方法。

At the php documentation http://www.php.net/manual/en/language.oop5.visibility.php#language.oop5.visibility-other-objects it says: 在php文档http://www.php.net/manual/en/language.oop5.visibility.php#language.oop5.visibility-other-objects中说:

Visibility from other objects 来自其他对象的可见性

Objects of the same type will have access to each others private and protected members even though they are not the same instances. 即使它们不是相同的实例,相同类型的对象也可以访问彼此私有和受保护的成员。 This is because the implementation specific details are already known when inside those objects. 这是因为在这些对象内部时已经知道实现特定的细节。

So this isn't a bug but a wanted feature of php. 所以这不是一个bug,而是一个想要的php功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM