同一个类的对象即使不是同一个实例也可以互相访问对方的私有与受保护成员。这是由于在这些对象的内部具体实现的细节都是已知的。
class 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'));
?>
以上例程会输出:
string(5) "hello"
Accessed the private method.
这是php手册讲同类实例访问私有属性的例子,类推公开和保护类型属性的也是能够访问的,能够访问的原因解释为‘这些对象的内部具体实现的细节都是已知的’,那么继承了父类后子类实例能访问父类实例的私有和保护类型吗?由下面例子演示:
class test{
public $param1 = 'public';
protected $param2 = 'protected';
private $param3 = 'prtvate';
}
class test1 extends test{
public function getParentParam($obj){
echo $obj->param1;
echo $obj->param2;
echo $obj->param3;
}
}
$test = new test();
$test1 = new test1();
$test1->getParentParam($test);
?>
输出结果为
publicprotected
致命错误:未捕获错误:无法访问/www/wwwroot/test.majunjun/index.php:11中的私有属性test :: $ param3堆栈跟踪:#0 /www/wwwroot/test.majunjun/index.php(16 ):test1-> getParentParam(Object(test))#1 {main}丢到第11行的/www/wwwroot/test.majunjun/index.php中
可见对于父类的私有属性访问还是有限制的。