Rumah  >  Artikel  >  pembangunan bahagian belakang  >  php 类与对象中的访问控制(可见性)

php 类与对象中的访问控制(可见性)

黄舟
黄舟asal
2017-07-02 10:47:331732semak imbas


类与对象 > 访问控制(可见性)  
同一个类的对象即使不是同一个实例也可以互相访问对方的私有与受保护成员。这是由于在这些对象的内部具体实现的细节都是已知的。

访问同一个对象类型的私有成员

<?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;));?>

//发现:通过传入实例对象,实现了在外部访问私有方法和属性

Atas ialah kandungan terperinci php 类与对象中的访问控制(可见性). Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn