php类设置属性

时间:2016-02-29 02:31:27

标签: class properties set

我无法理解这段代码:

$obj = new stdClass();
$obj->s = new stdClass();
$obj->s->p = new stdClass();
$obj->s->p->v = 1;
$obj->p = $obj->s->p;

echo $obj->s->p->v; //Return 1, OK
echo $obj->p->v; //Return 1, OK

$obj->p->v = 2; //Set the new value

echo $obj->p->v; //Return 2, OK
echo $obj->s->p->v; //Return 2, why??? I didn't set it!

我在不使用stdClass(真实类)的情况下测试了这段代码,结果是一样的。

请向我解释!

1 个答案:

答案 0 :(得分:1)

见这一行

user_id

这意味着您将$obj->p = $obj->s->p; 地址复制到$obj->s->p,因此它们都指向内存中的相同地址。因此,当您对$obj->p执行某些操作时,其更改也会反映在$obj->p