Copying and Cloning Objects

PHP Advanced and Object-OrientedProgrammingVisual Quickpro GuideLarry Ullman

class someClass
{
    public $val = 'a default value';
}
$a = new SomeClass();
$a->val = 11;
$b = $a;
echo $a->val;

//11

In PHP 5, when you create a copy of an object, PHP actually creates a new reference to that object, not an entirely new object. In other words, both variables will point to the same thing, and changes made through one object will be reflected by the other:
$a = new SomeClass();
$a->val = 1;
$b = $a;
$b->val = 2;
echo $a->val; // 2
More formally put, this means that PHP assigns objects by reference, not by value. PHP does this for performance reasons, as having multiple copies of entire objects, when not needed, is expensive.

 

posted @ 2016-08-29 09:03  papering  阅读(167)  评论(0编辑  收藏  举报