php - 堆栈无法转换为 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"
}
为什么会这样?
解决方案
从代码的这些行中获取线索:
//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();
这是你的选择。
推荐阅读
- scala - 如何使用 Spark/Scala 在 HDFS 上编写/创建 zip 文件?
- git - 我可以在 DataGrip 中使用现有的本地存储库吗?
- oracle - 带有预处理的 Apache NiFi JSON 到 SQL
- csv - 如何使用 JMeter 计算 CSV 文件中整数或双精度值的总和
- ffmpeg - FFmpeg 从没有音频的视频创建静音音频文件
- javascript - 当侦听器在文档上时获取所需的事件目标
- google-analytics - 谷歌分析奇怪的用户数
- xml - 这个符号怎么称呼?
- jupyter-notebook - nbconvert 不显示以编程方式生成的 Markdown 标头
- oracle - 在 pl/sql 中创建函数返回表