这是一个非常简单的类的2个版本。
只有bundle.getString("gcm.notification.aps");
功能在两个版本中有所不同。
getCounterIncrement()
class Counter {
protected $counter;
public function __construct() {
$this->counter = 0;
}
public function getCounterIncrement() {
return $this->counter++;
}
}
$counter = new Counter;
print $counter->getCounterIncrement(); // outputs 0
print $counter->getCounterIncrement(); // outputs 1
答案 0 :(得分:4)
++ $ a:预增量=>将$ a递增1,然后返回$ a。
$ a ++:后增量=>返回$ a,然后将$ a递增1。
在第一个版本中,首先返回值,然后递增(后增量)。因此,如果要返回递增的值,则必须使用预增量:
public function getCounterIncrement() {
return ++$this->counter;
}
答案 1 :(得分:3)
++
在变量名之前或之前的标准情况。如果它出现在变量名后面,那么在这种情况下,前一个值返回0。如果在变量之后得到变量,则先将其递增并返回该新值。
它们都不是更好的或更糟糕的方式,它只是两个不同的运算符,可以根据需要在不同的情况下使用。 Post-Increment
和Pre-Increment
他们被称为和减少相同。
<强> PHP Incrementing/Decrementing Operators 强>
我可能会重新写一点(尽管这不是更好的方法),就像这样
<?php
class Counter {
protected $counter;
public function __construct() {
$this->counter = 0;
}
public function incrementValue()
{
$this->counter++;
}
public function getValue() {
return $this->counter;
}
}
$counter = new Counter;
$counter->incrementValue();
print $counter->getValue();
P.S:看看你的个人资料我觉得你这个问题很有趣吗?
答案 2 :(得分:2)
在此行中,您在返回计数器后增加计数器:
return $this->counter++;
相反,你需要在返回之前增加它的值,如下所示:
return ++$this->counter;
答案 3 :(得分:1)
当你说例如i ++意味着使用i然后将其增加1.因此在第二个版本中它首先增加它然后返回它,这就是输出不同的原因。
答案 4 :(得分:1)
因为在第一个版本中,它的作用是uses
,然后递增相同的值。这就是为什么在第一个版本中它打印0,1和第二个版本1,2。
不,两者在编码标准方面都很好。这一切都取决于你想要使用的实现。
你已经写好了。它只是选择你喜欢/想要的方法。
答案 5 :(得分:1)
在第一个选项中,它首先返回当前值,然后递增。
在第二个选项中,它将在第一行更新,在下一行中返回更新的值。
希望你明白我说的话。
2和3个问题: 您可以在变量之前使用++,以便它更新然后返回值。但是我的代码中没有任何问题。
感谢。