类属性 和 实例属性 php,php 同一个类不同实例之间的属性访问

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

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中

可见对于父类的私有属性访问还是有限制的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值