PHP 中的引用赋值运算符,=&

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1768343/
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 03:46:27  来源:igfitidea点击:

Reference assignment operator in PHP, =&

phpoperatorsassignment-operator

提问by Kyle J. Dye

What does the =&(equals-ampersand) assignment operator do in PHP?

=&PHP中的(等号和号)赋值运算符有什么作用?

Is it deprecated?

它被弃用了吗?

回答by user56reinstatemonica8

It's not deprecated and is unlikely to be. It's the standard way to, for example, make part of one array or object mirror changes made to another, instead of copying the existing data.

它没有被弃用,也不太可能被弃用。例如,这是一种标准方法,可以将一个数组的一部分或对象镜像更改为另一个数组,而不是复制现有数据。

It's called assignment by reference, which, to quote the manual, "means that both variables end up pointing at the same data, and nothing is copied anywhere".

它被称为通过引用赋值,引用手册的话说,“这意味着两个变量最终都指向相同的数据,并且不会在任何地方复制任何内容”

The only thing that isdeprecated with =&is "assigning the result of newby reference" in PHP 5, which might be the source of any confusion. newis automatically assigned by reference, so &is redundant/deprecated in$o = &new C;, but not in $o = &$c;.

该唯一弃用与=&被“分配的结果new在通过引用” PHP 5,这可能是任何混淆的来源。new是通过引用自动分配的,因此在 中&是多余/不推荐使用的$o = &new C;,但在 中不是$o = &$c;



Since it's hard to search, note that =&(equals ampersand) is the same as = &(equals space ampersand) and is often written such that it runs into the other variable like $x = &$y['z'];or $x = &$someVar(ampersand dollar sign variable name). Example simplified from the docs:

由于很难搜索,请注意=&( equals &) 与= &( equals space ampersand)相同,并且通常写入时会遇到其他变量,例如$x = &$y['z'];or $x = &$someVar( & 美元符号变量 name)。从文档中简化的示例:

$a = 3;
$b = &$a;
$a = 4;
print "$b"; // prints 4


Here's a handy link to a detailed section on Assign By Referencein the PHP manual. That page is part of a series on references - it's worth taking a minute to read the whole series.

这是PHP 手册中有关按引用分配详细部分的便捷链接。该页面是参考系列的一部分 - 值得花一分钟阅读整个系列。

回答by Asaph

It's two different operators. =is assignment as you probably know. And &means the variable should be accessed by reference rather than by value.

这是两个不同的运营商。=是您可能知道的分配。并且&意味着应该通过引用而不是通过值访问变量。

回答by malcanso

$x = &$y['z'];

also has the effect of creating $y['z']if it doesn't exist, and setting it to null.

$y['z']如果它不存在,也有创建的效果,并将其设置为null.

This prevents error messages that you might have wanted to read. I haven't found documentation on this yet; possibly new in 5.3, for all I know.

这可以防止您可能想要阅读的错误消息。我还没有找到这方面的文档;据我所知,可能是 5.3 中的新内容。