【问题标题】:What does the ++ before something in php means [duplicate]php中某些东西之前的++是什么意思[重复]
【发布时间】:2012-01-22 05:39:54
【问题描述】:

可能重复:
Understanding Incrementing
Reference - What does this symbol mean in PHP?

++ 是什么意思,我在 javascript 中也看到过这个

$this->instance = ++self::$instances;

最好的问候

【问题讨论】:

标签: php


【解决方案1】:

PHP documentation 在这里很有帮助:

Example     Name               Effect
-----------------------------------------------------------------------
++$a        Pre-increment      Increments $a by one, then returns $a.
$a++        Post-increment     Returns $a, then increments $a by one.

你的代码相当于这样:

self::$instances = self::$instances + 1;
$this->instance = self::$instances;

【讨论】:

  • 嗯,不,不是……和$this->instance = self::$instances = self::$instances + 1一样。
  • ++foo 与 foo++ 不同。 ++foo:在其他操作之前递增, foo++:在其他操作之后递增。试试 bar = ++foo * 3 和 bar = foo++ * 3(foo 任意数字)。
  • 抱歉,编辑不会立即显示在 SO 上。不知道我在写第一个版本时在想什么。
  • 哇,你的意思是我也可以因为回答非常基本的问题而获得甜蜜的投票!?!?我得看看这个:)
  • 我实际上有 7 个帐户,并且对我发布七次的每个答案都投了赞成票。到目前为止没有人抓住我...
【解决方案2】:

【讨论】:

    【解决方案3】:

    $x 在这里被硬编码为 10,但很容易是用户输入的某个整数值。

    <?php    
        $x=10;
        $count=0;
        while($count<=10)
        {
            printf("<br/>%d", $x++);
            $count++;
        }// end while    
    ?>
    

    // 打印出 10 到 20.

    见$x++,这意味着使用x的值然后加1(++ --> x=x+1)。所以我们打印出 x 为 10,递增 1 并循环循环,打印出 11 递增 1 等等。现在如果我们有 ++$x,那么我们将首先递增然后打印出该值。因此,上面带有 ++$x 的相同代码将从 11-21 打印出来,因为当我们最初进入循环并且 x=10 时,它会递增到 11 然后打印。

    参见 $count++;,同样的概念。我用它作为计数器让 while 循环精确循环 10 次。 IT 等价于 count=count+1;虽然将 ++ 放在 $x 的左侧或右侧确实很重要,但对于 count 来说并不重要,因为我们没有使用 count 或将其打印出来。因此,如果我在上面的代码中有 ++$count,它将执行完全相同。

    【讨论】:

      猜你喜欢
      • 2023-03-27
      • 1970-01-01
      • 2018-04-09
      • 2012-10-24
      • 1970-01-01
      • 2021-12-05
      • 2017-09-13
      • 1970-01-01
      • 2012-02-12
      相关资源
      最近更新 更多