“所以$分配也将有& $实例”
关闭。 $ assigned将成为引用与$实例在赋值时引用的相同内容的引用。
换句话说:
<?php
$instance = new SimpleClass();
$assigned = $instance; //$assigned now references SimpleClass instance (NOT $instance)
//Other than both pointing the same thing, the two variables are not related at all (sort of... :p)
$reference =& $instance;
//$reference does not point at the SimpleClass instance like $assigned does, but rather it points at $instance which points at the SimpleClass instance. It is, in a sort of incorrect way, a reference to the reference.
//$instance still references the SimpleClass instance here, so it does what you'd expect
$instance->var = '$assigned will have this value';
$instance = null; // $instance and $reference become null
//They both become null because $reference references $instance. In the same way that:
$a = 5;
$b =& $a;
$a = 3; //$b now equals 3.
//Since the reference held in $instance is wiped, $reference's value is wiped too (since it points to that same reference
这一点的一个令人费解的解释,我很害怕,但希望它横跨得到点。重点是:变量不存储对象;变量引用对象。对象不会默认复制,而是复制引用。
$ a = new ...; $ b = $ a;
这将复制引用,而不是对象。 $ b =克隆$ a;会复制对象。
如果您对Java很熟悉,就好像在Java中一样,对象通过引用传递给方法,但引用是按值传递的(引用被复制)。
$赋值给引用复制,$引用引用引用对象的变量。