一起源码网

标题: php 类与对象中的访问控制(可见性) [打印本页]

作者: 云文章    时间: 2020-3-18 04:30
标题: php 类与对象中的访问控制(可见性)


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

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

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

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

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

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

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

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


作者: 忙狗    时间: 2022-9-8 17:34
利用网页源代码下载免费文件




欢迎光临 一起源码网 (https://www.171739.xyz/) Powered by Discuz! X3.3