为什么 1 +递减值 + 1 = 2?
我找到了一段代码(来自我们的一位开发人员),我想知道为什么它的输出是 2?
<?php
$a = 1;
$a = $a-- +1;
echo $a;
谢谢
I found a piece of code (from one of our developer) and I was wondering why the output of this is 2?
<?php
$a = 1;
$a = $a-- +1;
echo $a;
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会尝试一下我的解释。我们正在讨论引用系统中某些值的变量。
因此,当您定义
$a = 1
时,您将变量$a
指向内存中某处的值1
。在第二行中,您正在执行
$a = $a-- + 1
,因此您创建一个新值并将其设置为$a
。$a--
检索原始$a
的值,即1
并添加1
以使2
并在内存中的其他位置创建该值。所以现在你有一个变量$a
,它指向2
和内存中的其他值1
,它一路递减到0
,但没有任何东西再指向它了,所以谁在乎呢。然后您回显
$a
,它指向您的值2
。编辑:测试页面
I'll give my explanation a whirl. We're talking about a variable referencing some value off in the system.
So when you define
$a = 1
, you are pointing the variable$a
to a value1
that's off in memory somewhere.With the second line, you are doing
$a = $a-- + 1
so you are creating a new value and setting that to$a
. The$a--
retrieves the value of the original$a
, which is1
and adds1
to make2
and creates that value somewhere else in memory. So now you have a variable$a
which points to2
and some other value1
off in memory which along the way decremented to0
, but nothing is pointing at it anymore, so who cares.Then you echo
$a
which points to your value of2
.Edit: Testing Page
$a-- 在该行执行后减少值。要得到答案 1,您可以将其更改为 --$a
$a-- decrements the value after the line executes. To get an answer of 1, you would change it to --$a
什么?
只是为了澄清其他答案,您在这一行中发生了什么:
基本上,当 PHP 计算 $a-- 时,它实际上返回 $a 的值,然后运行递减它的操作。
尝试一下
当您运行此代码时,您将看到该数字仅在返回后才递减。所以使用这个逻辑,就更清楚为什么
会输出 2 而不是 1。
更好的方法
也许更好的方法,可以说更清楚的是
What the?
Just to clarify the other answers, what you have going on in this line:
Basically when PHP evaluates $a--, it actually returns the value of $a, and then runs the operation of decrementing it.
Try this
When you run this code, you will see that the number only decrements after it has been returned. So using this logic, it's a bit more clear why
would output 2 instead of 1.
A better way
Perhaps a better way, arguably more clear would be
上面的内容相当于:
这实际上几乎就是 PHP 在幕后将其翻译成的内容。所以
$a--
并不是一个有用的操作,因为$a
无论如何都会被覆盖。最好将其替换为$a - 1
,使其更清晰并消除额外的操作。The above is equivalent to something like:
That actually pretty much what PHP translates that into, behind the scenes. So
$a--
is not such a useful operation, since$a
is going to be overwritten anyway. Better simply replace that with$a - 1
, to make it both clearer and to eliminate the extra operation.