我知道这在php文档中有所涉及,但我对此问题感到困惑.
来自php文档:
$instance = new SimpleClass();
$assigned = $instance;
$reference =& $instance;
$instance->var = '$assigned will have this value';
$instance = null; // $instance and $reference become null
var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>
Run Code Online (Sandbox Code Playgroud)
上面的例子将输出:
NULL
NULL
object(SimpleClass)#1 (1) {
["var"]=>
string(30) "$assigned will have this value"
}
Run Code Online (Sandbox Code Playgroud)
好的,所以我看到$assigned
幸存的原始对象($instance
)被分配给了null
,所以显然$assigned
不是引用而是$ instance的副本.
那么有什么区别呢
$assigned = $instance
Run Code Online (Sandbox Code Playgroud)
和
$assigned = clone $instance
Run Code Online (Sandbox Code Playgroud)
dec*_*eze 20
对象是内存中的抽象数据.变量始终在内存中保存对此数据的引用.想象一下,在内存中$foo = new Bar
的Bar
某个地方创建一个对象实例,为它分配一些id #42
,$foo
现在将其#42
作为对象的引用.通过引用将此引用分配给其他变量,或者通常与任何其他值相同.许多变量可以保存此引用的副本,但都指向同一个对象.
clone
显式创建对象本身的副本,而不仅仅是指向对象的引用.
$foo = new Bar; // $foo holds a reference to an instance of Bar
$bar = $foo; // $bar holds a copy of the reference to the instance of Bar
$baz =& $foo; // $baz references the same reference to the instance of Bar as $foo
Run Code Online (Sandbox Code Playgroud)
只是不要将"引用" =&
与"引用" 混淆,如对象标识符.
$blarg = clone $foo; // the instance of Bar that $foo referenced was copied
// into a new instance of Bar and $blarg now holds a reference
// to that new instance
Run Code Online (Sandbox Code Playgroud)
和...之间的不同
$assigned = $instance
Run Code Online (Sandbox Code Playgroud)
和
$assigned = clone $instance
Run Code Online (Sandbox Code Playgroud)
就是当你使用clone关键字时,你可以使用魔术方法__clone(),它可以更好地控制对象克隆.来自php手册:
克隆完成后,如果定义了__clone()方法,则将调用新创建的对象的__clone()方法,以允许任何需要更改的必要属性.
此外,如果要创建应使用clone的对象副本,则通过引用分配PHP 5中的对象.
来自手册:
PHP引用是一个别名,它允许两个不同的变量写入相同的值.从PHP 5开始,对象变量不再包含对象本身作为值.它只包含一个对象标识符,允许对象访问者查找实际对象.当一个对象通过参数发送,返回或分配给另一个变量时,不同的变量不是别名:它们包含标识符的副本,该副本指向同一个对象.