PHP 的 =& 运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5930177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:55:38  来源:igfitidea点击:

PHP's =& operator

phpassignment-operator

提问by Kev

Are both these PHP statements doing the same thing?:

这两个 PHP 语句都在做同样的事情吗?:

$o =& $thing;

$o = &$thing;

采纳答案by judda

Yes, they are both the exact same thing. They just take the reference of the object and reference it within the variable $o. Please note, thingshould be variables.

是的,它们是完全相同的东西。他们只是获取对象的引用并在变量中引用它$o。请注意,thing应该是变量。

回答by Scott Lahteine

They're not the same thing, syntactically speaking. The operator is the atomic =&and this actually matters. For instance you can't use the =&operator in a ternary expression. Neither of the following are valid syntax:

从语法上讲,它们不是一回事。运算符是原子=&,这实际上很重要。例如,您不能在三元表达式中使用=&运算符。以下都不是有效的语法:

$f = isset($field[0]) ? &$field[0] : &$field;
$f =& isset($field[0]) ? $field[0] : $field;

So instead you would use this:

所以你会使用这个:

isset($field[0]) ? $f =& $field[0] : $f =& $field;

回答by Rich Bradshaw

They both give an expected T_PAAMAYIM_NEKUDOTAYIM error.

它们都给出了预期的 T_PAAMAYIM_NEKUDOTAYIM 错误。

If you meant $o = &$thing;then that assigns the reference of thing to o. Here's an example:

如果您的意思$o = &$thing;是将事物的引用分配给 o。下面是一个例子:

$thing = "foo";

$o = &$thing;

echo $o; // echos foo

$thing = "bar";

echo $o; // echos bar

回答by bbe

The difference is very important:

区别非常重要:

<?php
$a = "exists";
$b = $a;
$c =& $a;
echo "a=".$a.", b=".$b.", c=".$c."<br/>"; //a=exists b=exists c=exists

$a = null;
echo "a=".$a.", b=".$b.", c=".$c; //a= b=exists c= 
?>

Variable $c dies as $a becomes NULL, but variable $b keeps its value.

变量 $c 在 $a 变为 NULL 时消失,但变量 $b 保持其值。

回答by Emil Vikstr?m

Yes, they do. $owill become a referenceto thingin both cases (I assume that thingis not a constant, but actually something meaningful as a variable).

是的,他们这样做。$o将成为一个参考,以thing在这两种情况下(我认为thing是不是一个恒定的,但实际上一些有意义的事情作为一个变量)。

回答by Karl Laurentius Roos

If you meant thingwith a $before them, then yes, both are assigning by reference. You can learn more about references in PHP here: http://www.php.net/manual/en/language.references.whatdo.php

如果您的意思thing$在它们之前加上 a ,那么是的,两者都是通过引用分配的。您可以在此处了解有关 PHP 引用的更多信息:http: //www.php.net/manual/en/language.references.whatdo.php