堆栈无法转换为int

时间:2018-11-21 07:45:17

标签: php oop

我有以下代码

public function account(Stack $volume) {
    //echo $volume->value();  //This line prints 300
    //echo $this -> balance(); //This line prints 400
    //echo gettype($volume -> value()); //int
    //echo gettype($this->balance());  //object
    echo $this -> balance() + $volume -> value(); // This line prints "Notice: Object of class Stack could not be converted to int"
}

为什么会这样?

1 个答案:

答案 0 :(得分:3)

从代码的以下几行中获取线索:

//echo $this -> balance(); //This line prints 400
...
//echo gettype($this->balance());  //object

这意味着$this->balance()返回的对象可以转换为带有数字值的字符串,该字符串在您的代码中为400。 要将其转换为整数,可以使用strval(),然后使用intval(),如下所示:

echo intval(strval($this -> balance())) + $volume -> value();

由于+运算符还可以使用字符串中的数字值,因此仅strval()也可以使用:

echo strval($this -> balance()) + $volume -> value();

由您选择。