时间:2021-07-01 10:21:17 帮助过:19人阅读
我们从下面的示例来分析
PHPclass A {};class B {};$a = new A;$b = $a; $b->testA = "Changed Class A";/* * 此时$a,$b的关系: * +-----------+ +-----------------+ * $a --> | object id | ---> | object(Class A) | * +-----------+ +-----------------+ * ^ * +-----------+ | * $b --> | object id | ---------+ * +-----------+ * * */$c = new B;$a = $c;$a->testB = "Changed Class B";/* * 此时$a,$b,$c的关系: * +-----------+ +-----------------+ * $b --> | object id | ---> | object(Class A) | * +-----------+ +-----------------+ * * +------------+ * $a --> | object id2 | -------------+ * +------------+ | * v * +------------+ +-----------------+ * $c --> | object id2 | ---> | object(Class B) | * +------------+ +-----------------+ */echo "object a: "; var_dump($a); //["testB"]=> string(15) "Changed Class B"echo "object b: "; var_dump($b); //["testA"] => string(15) "Changed Class A"echo "object c: "; var_dump($c); //["testB"]=> string(15) "Changed Class B"//如果对象是按照引用传递的,那么$a, $b, $c输出的内容应该一样,事实上结果并非如此。 看下面通过引用传递对象的列子:testA = 2;/* * 此时$aa, $bb的关系: * * +-----------+ +-----------------+ * $bb --> | object id | ---> | object(Class A) | * +-----------+ +-----------------+ * ^ * | * $aa ---------+ * * */$cc = new B;$aa = $cc;$aa->testB = "Changed Class B";/* * 此时$aa, $bb, $cc的关系: * * +-----------+ +-----------------+ * | object id | ---> | object(Class A) | * +-----------+ +-----------------+ * * $bb ---->-----+ * | * $aa ---->-----+ * | * v * +------------+ * | object id2 | --------------+ * +------------+ | * v * +------------+ +-----------------+ * $cc --> | object id2 | ---> | object(Class B) | * +------------+ +-----------------+ */echo "object aa: "; var_dump($aa); //["testB"]=>string(15) "Changed Class B"echo "object bb: "; var_dump($bb); //["testB"]=>string(15) "Changed Class B"echo "object cc: "; var_dump($cc); //["testB"]=>string(15) "Changed Class B"//此时$aa,$bb,$cc三者内容完全一样,所以可以看出对象默认并不是按照引用传递,要尽快走出这个误区。
参考文章:http://php.com/manual/zh/language.oop5.references.php
http://weizhifeng.net/php-reference.html