开发者

How to make reference to a parent object property in the cloned object in PHP 5.3?

I want to do this:

class T
{
    public $a;
    public $b;
    public function __construct()
    {
        $this->a = new P;
        $this->b = clone $this->a;
    }
}

class P
{
    public $name ="Chandler";
    publ开发者_Go百科ic function __clone()
    {
        $this->name = & $that->name;
    }

}

$tour = new T;
$tour->a->name = "Muriel";

?>

But after this, $tour->b->name will be NULL, why ?

How can I make the clone name property reference to the parent object name property, so when I change the parent object name, the cloned object name will change accordingly ?


From the php.net cloning manual page,

When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references.

but $name is a scalar variable (a string) and not an object. So when you clone $a to $b, $a->name and $b->name are distinct variables. ie) $b->name does not reference $a->name

In short, I do not believe that it is possible (please correct me if I am wrong). However, you could cheat and do something like:

class P
{
    public $name;
    public function __construct(){
        $this->name = new StdClass();
        $this->name->text = 'Chandler';
    }   
}

Then $a->name->text = 'Muriel'; will also change $b->name->text.


$that doesn't exist in the __clone function as said in George Schlossnagle: Advanced PHP Programming book... It gave me a couple of weeks headache... So, you can do this with a simple trick in the constructor (in class P); make the variable reference to himself:

function __construct()
{
    $this->name = & $this->name;
}

this works in PHP 5.3.6. I did not test it in other versions. So when you do $tour->a->name = "Muriel";, then $tour->b->name will be "Muriel" too!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜