在 PHP 中将对象转换为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/583157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:08:47  来源:igfitidea点击:

Convert object to integer in PHP

phptypes

提问by ryonlife

  • The value of $total_results = 10
  • $total_results in an object, according to gettype()
  • I cannot use mathematical operators on $total_results because it's not numeric
  • Tried $total_results = intval($total_results) to convert to an integer, but no luck
  • The notice I get is: Object of class Zend_Gdata_Extension_OpenSearchTotalResults could not be converted to int
  • $total_results 的值 = 10
  • $total_results 在一个对象中,根据 gettype()
  • 我不能在 $total_results 上使用数学运算符,因为它不是数字
  • 尝试 $total_results = intval($total_results) 转换为整数,但没有运气
  • 我得到的通知是:类 Zend_Gdata_Extension_OpenSearchTotalResults 的对象无法转换为 int

How can I convert to an integer?

如何转换为整数?

回答by Sean Bright

Does this work?

这行得通吗?

$val = intval($total_results->getText());

回答by Karsten

$results_numeric = (int) $total_results;

or maybe this:

或者这个:

$results_numeric = $total_results->count();

回答by Pim Jager

perhaps the object has a build in method to get it as an integer?

也许该对象有一个内置方法可以将其作为整数获取?

Otherwise try this very hacky approach (relys on __toString() returning that 10)

否则尝试这种非常hacky的方法(依赖于 __toString() 返回 10)

$total_results = $total_results->__toString();
$total_results = intval($total_results);

However if the object has a build in non-magic method, you should use that!

但是,如果对象具有内置的非魔法方法,则应该使用它!

回答by Morten Christiansen

You can see the methods of the class here. Then you can try out the different methods yourself. There is a getText() method for example.

您可以在此处查看该类的方法。然后你可以自己尝试不同的方法。例如,有一个 getText() 方法。

回答by CodeXP

try

尝试

class toValue {
    function __toString()
    {
        return '3'; // you must return a string
    }
}

$a = new toValue;

var_dump("$a" + 2);

result: int(5)

结果:int(5)