php 通过引用传递不起作用
我只是想通过尝试在 php.net 上找到的一些示例来理解 PHP 中的引用传递。我在 php 网站上找到了一个示例,但它不起作用:
function foo(&$var)
{
return $var++;
}
$a=5;
echo foo($a); // Am I not supposed to get 6 here? but I still get 5
这是一个找到的示例 这里
谁能告诉我为什么变量 $a 得到的是 5 而不是 6?
I'm just trying to understand passing by reference in PHP by trying some examples found on php.net. I have one example right here found on the php website but it does not work:
function foo(&$var)
{
return $var++;
}
$a=5;
echo foo($a); // Am I not supposed to get 6 here? but I still get 5
This is an example found here
Can anybody tell me why am I getting 5 instead of 6 for the variable $a?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
你的代码和示例代码不一样。他们的行为有所不同,这奇怪吗?
要看到您期望的行为,您必须将
$var++
更改为++$var
。这里发生的情况是,虽然函数返回后
$a
的值为 6,但由于后置自增运算符 ($var++
) 有效。您可以使用以下方法进行测试:Your code and the example code is not the same. Is it a wonder they behave differently?
To see the behavior you expect, you have to change
$var++
to++$var
.What happens here is that while the value of
$a
is 6 after the function returns, the value that is returned is 5 because of how the post-increment operator ($var++
) works. You can test this with:因为
$a++
返回$a
然后加一。要执行您想要执行的操作,您需要执行
++$a
。http://www.php.net/manual/en/language.operators .increment.php
Because
$a++
returns$a
then increments by one.To do what you are trying to do you will need to do
++$a
.http://www.php.net/manual/en/language.operators.increment.php
这是与增量运算符有关,而不是通过参考。如果您查看手册,您将看到展示您想要的行为,您必须更改 foo() 以使用前增量而不是后增量,如下所示:
现在:
This is to do with the increment operator, rather than passing by reference. If you check the manual, you'll see to exhibit the behaviour you desire, you must change
foo()
to use pre-increment instead of post-increment, like so:Now:
不,这很好用。
$var++
返回$var
的值,然后递增变量。因此返回值是5
,这就是您echo
的内容。不过,变量$a
现在已更新为6
。No, this works just fine.
$var++
returns the value of$var
, then increments the variable. So the returned value is5
, which is what youecho
. The variable$a
is now updated to6
though.尝试回显实际变量:
如果您在返回之前递增,则您的示例将起作用:
Try echoing the actual variable:
If you increment before you return, your example will work though:
与问题没有直接关系,仅与主题相关。
似乎确实存在 PHP 错误...
输出:
not directly related to the question, only the subject.
There does seem to be a PHP bug ...
outputs: