gpt4 book ai didi

php - 是否需要在对象前使用&符号?

转载 作者:可可西里 更新时间:2023-11-01 13:14:39 24 4
gpt4 key购买 nike

由于对象现在默认通过引用传递,是否有一些特殊情况下 &$obj 有意义?

最佳答案

对象使用不同的引用机制。 &$object 更像是一个引用的引用。你不能真正比较他们两个。参见 Objects and references :

A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP 5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.

&$object 不同于 $object。我给你举个例子:

foreach ($objects as $object) {
if ($cond) {
$object = new Object(); // This won't affect $objects

}
}

foreach ($objects as &$object) {
if ($cond) {
$object = new Object(); // This will affect $objects

}
}

我不会回答这个问题是否有意义,或者是否有需要。这些是基于意见的问题。你绝对可以在没有对象的 & 引用的情况下生活,就像你根本没有对象一样。两种机制的存在是 PHP 向后兼容的结果。

关于php - 是否需要在对象前使用&符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21058439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com