首頁  >  文章  >  後端開發  >  php 類別與物件中的存取控制(可見性)

php 類別與物件中的存取控制(可見性)

黄舟
黄舟原創
2017-07-02 10:47:331732瀏覽


類別與物件 > 存取控制(可見性)  
同一個類別的物件即使不是同一個實例也可以互相存取對方的私有與受保護成員。這是由於在這些物件的內部具體實現的細節都是已知的。

存取同一個物件類型的私有成員

<?phpclass Test{
    private $foo;    public function construct($foo)
    {
        $this->foo = $foo;
    }    private function bar()
    {
        echo &#39;Accessed the private method.&#39;;
    }    public function baz(Test $other)
    {
        // We can change the private property:
        $other->foo = &#39;hello&#39;;
        var_dump($other->foo);        // We can also call the private method:
        $other->bar();
    }
}$test = new Test(&#39;test&#39;);$test->baz(new Test(&#39;other&#39;));?>

//發現:透過傳入實例物件,實現了在外部存取私有方法和屬性

類別與物件> 存取控制(可見性)  
同一個類別的物件即使不是同一個實例也可以互相存取對方的私有與受保護成員。這是由於在這些物件的內部具體實現的細節都是已知的。

存取同一個物件類型的私有成員

<?phpclass Test{
    private $foo;    public function construct($foo)
    {
        $this->foo = $foo;
    }    private function bar()
    {
        echo &#39;Accessed the private method.&#39;;
    }    public function baz(Test $other)
    {
        // We can change the private property:
        $other->foo = &#39;hello&#39;;
        var_dump($other->foo);        // We can also call the private method:
        $other->bar();
    }
}$test = new Test(&#39;test&#39;);$test->baz(new Test(&#39;other&#39;));?>

//發現:透過傳入實例物件,實現了在外部存取私有方法和屬性

以上是php 類別與物件中的存取控制(可見性)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn