类与对象 youjiankuohaophpcn 访问控制(可见性)
同一个类的对象即使不是同一个实例也可以互相访问对方的私有与受保护成员。这是由于在这些对象的内部具体实现的细节都是已知的。
访问同一个对象类型的私有成员
立即学习“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'));?>//发现:通过传入实例对象,实现了在外部访问私有方法和属性
类与对象 > 访问控制(可见性)
同一个类的对象即使不是同一个实例也可以互相访问对方的私有与受保护成员。这是由于在这些对象的内部具体实现的细节都是已知的。
访问同一个对象类型的私有成员
立即学习“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'));?>//发现:通过传入实例对象,实现了在外部访问私有方法和属性
以上就是php 类与对象中的访问控制(可见性)的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号