函数以“&”作为参数传递$x”输出一个值而不是错误,请参阅下面的代码
下面的代码输出“15”,为什么?
function zz(&$x){
$x = $x + 5;
}
$x = 10;
zz($x);
echo $x;
请解释一下
Below is the code which outputs "15", why?
function zz(&$x){
$x = $x + 5;
}
$x = 10;
zz($x);
echo $x;
Please explain
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
按设计工作。通过使用
&
,您可以通过引用传递$x
,这意味着函数对变量执行的任何操作都将针对原始$x
执行设置为10
。如果您使用
原始的
$x
将保留在10
,因为只有变量 value 被传递给函数。Works as designed. By using
&
you pass$x
by reference, meaning that anything the function does to the variable, will be done to the original$x
that is set to10
.If you used
the original
$x
would stay at10
, because only the variable value is passed to the function.您传递的值作为参数不是变量的直接值,而是通过引用传递,因此它为您提供 15 作为输出。
谢谢!
you are passing the value as argument is not direct value of the variable but its passing By reference, so its giving you 15 as a output.
Thanks!
因为函数签名定义了传递给函数的值应该通过引用传递。
如果您不知道这意味着什么,我建议您阅读维基百科上的这段。
Because the function signature defines that the value passed to the function should be passed by reference.
If you don't know what that means, I suggest to read this paragraph on Wikipedia.
添加 &意味着您正在通过引用传递 $x 变量。外部的值在函数内更改,而不是在函数内更改副本。
Adding a & means you are passing the $x variable by reference. The value outside is changed within the function, instead of a copy within the function being changed.
函数内部的
$x
是对与函数外部的$x
相同值的引用。当函数接受带有“&”的参数时,它的值不会复制到函数作用域内创建的新变量中,而是对与给定参数相同值的引用。
请参阅此处。
$x
inside the function is a reference to the same value as$x
outside your function.When a function accepts a parameter with a "&", it's value is not copied into the new variable created inside the function's scope, but is a reference to the same value as the argument that was given.
See here.
使用 & & 符号:通过引用传递满足函数中的目的。
它只是简单地改变原始变量并再次将其返回到相同的变量名称并分配新值。
Using & Ampersand: Passing by Reference mets the purpose in the function.
Its simply alter the original variable and return it again to the same variable name with its new value assigned.