<?php
$c1 = new myclass();
$c2 = $c1;
$c3 = &$c1;
$c1 = null;
var_dump($c1);
var_dump($c2);
var_dump($c3);
?>
output
NULL
object(myclass)#1 (1) { ["v1"]=> int(2) }
NULL
<?php
$c1 = new myclass();
$c2 = $c1;
$c3 = &$c1;
unset($c1);
var_dump($c1);
var_dump($c2);
var_dump($c3);
?>
output
NULL
object(myclass)#1 (1) { ["v1"]=> int(2) }
object(myclass)#1 (1) { ["v1"]=> int(2) }
标识符=>地址
$c1是个标识符
$c2也是个标识符 和$c1一样 对应同一个地址
$c3是$c1的别名
$c1 = null
变量$c1依然存在 只是指示的内容变了
$c3跟着变
unset($c1);
销毁变量$c1
但是$c3依然指向对象
如果要拷贝的对象引用了其他的对象资源,要实现深拷贝,必须实现自定义的__clone()方法,并在__clone方法中,对相关对象实现深拷贝。
Example #1 Cloning an object
<?php
class SubObject
{
static $instances = 0;
public $instance;
public function __construct(){
$this->instance =++self::$instances;
}
public function __clone(){
$this->instance =++self::$instances;
}
}
class MyCloneable
{
public $object1;
public $object2;
function __clone()
{
// Force a copy ofthis->object, otherwise
// it will pointto same object.
$this->object1 =clone $this->object1;
}
}
$obj =new MyCloneable();
$obj->object1 =new SubObject();
$obj->object2 =new SubObject();
$obj2 =clone $obj;
print("OriginalObject:\n");
print_r($obj);
print("ClonedObject:\n");
print_r($obj2);
?>
The above example will output:
Original Object:
MyCloneable Object
(
[object1] => SubObject Object
(
[instance] => 1
)
[object2] => SubObject Object
(
[instance] => 2
)
)
Cloned Object:
MyCloneable Object
(
[object1] => SubObject Object
(
[instance] => 3
)
[object2] => SubObject Object
(
[instance] => 2
)
)
转载于:https://blog.51cto.com/boogle/883472