douchenchepan6465 2013-05-04 14:24
浏览 25
已采纳

增加“__toString”

I am not sure what the title should be, but the code should explain it better:

class Group {
    private $number = 20;

    public function __toString() {
        return "$this->number";
    }
}

$number = new Group();
echo $number, PHP_EOL;
echo ++ $number, PHP_EOL;

echo PHP_EOL;

$number = "20";
echo $number, PHP_EOL;
echo ++ $number, PHP_EOL;

echo PHP_EOL;

$number = 20;
echo $number, PHP_EOL;
echo ++ $number, PHP_EOL;

Output:

20
20              <--- Expected 21

20
21

20
21

Any idea why I got 20 instead of 21? Even then the code below works:

$i = null ;
echo ++$i ; // output 1

I know Group is an object that implements __toString , i expected ++ to work with the string from __toString or at least throw an error

  • 写回答

5条回答 默认 最新

  • douyan1613 2013-05-04 16:52
    关注

    The order in which the operations happen is important:

    1. The variable will be fetched as an object, it won't be casted to an integer (or something else).

    2. This ++ operator increments the lval (the long value) of the zval, but does normally nothing else. The object pointer remains the same. The internal (fast_)increment_function will be called with the zval which has a pointer to the object, which checks for the type first. If it's an object, it does nothing. So when your zval is an object, it is as useful as a no-operation. This won't output any warning.

    3. Only then the echo instruction performs a string cast on his arguments: The __toString method is called and returns 20.

    4. 20 will be output.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用