类与对象 > 访问控制(可见性)
同一个类的对象即使不是同一个实例也可以互相访问对方的私有与受保护成员。这是由于在这些对象的内部具体实现的细节都是已知的。
访问同一个对象类型的私有成员<?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'));?>
//发现:通过传入实例对象,实现了在外部访问私有方法和属性