提问者:小点点

为什么可以在对象内同一类的对象实例上设置私有成员?


有人能解释为什么我能在TestFoo::getFooInstance()中设置私有成员$bar

TestFoo::getFo2Instance()但是返回一个致命错误。

我总是假设私有成员应该只能从同一个对象实例而不是同一个对象类访问?

<?php

class TestFoo  {

    private $bar;

    public static function getFooInstance()
    {
        $instance = new TestFoo();
        $instance->bar = "To bar or not to bar";
        return $instance;
    }

    public static function getFoo2Instance()
    {
        $instance = new TestFoo2();
        $instance->bar = "To bar or not to bar";
        return $instance;
    }

    public function getBar()
    {
        return $this->bar;
    }
}

class TestFoo2 {
    private $bar;
    public function getBar()
    {
        return $this->bar;
    }
}

$testFoo = TestFoo::getFooInstance();
echo $testFoo->getBar();

// returns PHP fatal error
//$testFoo2 = TestFoo::getFoo2Instance();
//echo $testFoo2->getBar();
?>

共1个答案

匿名用户

protected私有属性背后的思想是,类希望隐藏这些属性,不让外部代码知道。不是作为安全性的度量,而是因为这些属性仅供类内部使用,不应该是其他代码的公共接口。任何公共的都可以被其他代码使用,并且应该保持不变,以防止其他代码中断。私有的受保护的属性和方法只能由类本身使用,所以如果需要重构或更改它们,这些更改保证是本地化到类本身的,并且保证不会破坏任何其他内容。

因此,允许类修改属性并调用其类型的任何对象实例的方法,因为可以信任类本身了解其自身的实现。