PHP's =& operator

谁说胖子不能爱 提交于 2019-11-27 05:33:38

问题


Are both these PHP statements doing the same thing?:

$o =& $thing;

$o = &$thing;

回答1:


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, thing should be variables.




回答2:


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;



回答3:


They both give an expected T_PAAMAYIM_NEKUDOTAYIM error.

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

$thing = "foo";

$o = &$thing;

echo $o; // echos foo

$thing = "bar";

echo $o; // echos bar



回答4:


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.




回答5:


If you meant thing with 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




回答6:


Yes, they do. $o will become a reference to thing in both cases (I assume that thing is not a constant, but actually something meaningful as a variable).



来源:https://stackoverflow.com/questions/5930177/phps-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!