在下面的示例中,$instance2
和$instance3
完成的任何操作都会修改原始对象。
我的问题是:
如果原始对象标识符的副本和对原始对象标识符的引用执行相同的工作,应该在实际应用程序中使用哪一个?
使用对象标识符副本和使用对象标识符的引用有哪些优缺点?
我阅读PHP manual但无法区分使用方法,因为两者都做同样的工作。
$instance1 = new test(1);
$instance2 = $instance1;
$instance3 =& $instance1;
//$instance1 -> original object identifier of the new object.
//$instance2 -> copy of object identifier $instance1
//$instance3 -> reference to the object identifier $instance1
答案 0 :(得分:6)
$instance2
具有对象测试的标识符副本。因此,它包含与$instance1
相同的内容。
$instance3
包含对$instance1
的引用。不同之处如下:
$instance1 = new Test();
$instance2 = $instance1;
$instance3 = & $instance1;
var_dump($instance1 instanceof Test); // True
var_dump($instance2 instanceof Test); // True
var_dump($instance3 instanceof Test); // True
$instance3 = new AnotherTest();
var_dump($instance1 instanceof AnotherTest); // True
var_dump($instance2 instanceof AnotherTest); // False
var_dump($instance3 instanceof AnotherTest); // True
如果更改了$instance1
而不是$instance3
,则会返回相同的输出。
但如果我们做了以下事情:
$instance1 = new Test();
$instance2 = $instance1;
$instance3 = & $instance1;
$instance2 = new AnotherTest();
var_dump($instance1 instanceof AnotherTest); // False
var_dump($instance2 instanceof AnotherTest); // True
var_dump($instance3 instanceof AnotherTest); // False
所以:
通过引用传递或通过引用传递的变量(使用&
操作数)或它引用的变量的修改,修改两者,而复制变量的修改仅修改给定变量
但是,你必须记住$instance1
保留的是对象的标识符,所以:
$instance1 = new StdClass();
$instance2 = $instance1;
$instance1->my_property = 1;
var_dump($instance2->my_property); // Output: 1
希望现在更清楚了。
答案 1 :(得分:0)
对于PHP5中的对象,而不是整个对象,只复制对象标识符。这使得您不再需要引用相同的值,而只需复制标识符以引用同一个对象。使用它对您有利;你可以摆脱&符号。
一个重要的区别是赋值给变量引用会影响原始变量,而赋值给复制的对象标识符则不会。只对对象进行修改。如果您想以直观的方式使用OO,这将是不使用对象引用的原因。例如:
$a = new stdClass();
$a->name = "A";
$b = new stdClass();
$b->name = "B";
// $x is a copy of the object identifier in $a
$x = $a;
// $y is a reference to $a
$y = &$a;
// this will not affect $a
$x = $b;
echo $a->name; // 'A'
// this will affect $a
$y = $b;
echo $a->name; // 'B'
另请参阅本文,了解为何应避免使用(&符号)引用:
http://schlueters.de/blog/archives/125-Do-not-use-PHP-references.html