首页 > 解决方案 > 堆栈无法转换为 int

问题描述

我有以下代码

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"
}

为什么会这样?

标签: phpoop

解决方案


从代码的这些行中获取线索:

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

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

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

因为+运算符也可以处理字符串中的数值,juststrval()也可以:

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

这是你的选择。


推荐阅读