在"__toString"上增加 [英] Increment on "__toString"

查看:85
本文介绍了在"__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;

输出:

20
20              <--- Expected 21

20
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

我知道Group是实现__toString的对象,我希望++__toString或至少throw an error

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

推荐答案

操作发生的顺序很重要:

The order in which the operations happen is important:

  1. 该变量将作为对象获取,不会被强制转换为整数(或其他).

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

++运算符增加zvallval(长值),但通常不执行其他任何操作.对象指针保持不变.内部(fast_)increment_function将用zval调用,该zval具有一个指向对象的指针,该对象首先检查类型.如果是对象,则不执行任何操作.因此,当zval是对象时,它与无操作一样有用.这不会输出任何警告.

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.

然后,echo指令才对他的参数执行字符串转换:__toString方法被调用并返回20.

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

20将被输出.

这篇关于在"__toString"上增加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆