【问题标题】:Multiply float(7.2) for simpleXML with PHP5.6将 simpleXML 的 float(7.2) 与 PHP5.6 相乘
【发布时间】:2019-05-16 09:16:37
【问题描述】:

我正在尝试在面向对象的 PHP 项目中为 XML 文件做一个简单的乘法运算。

在 MariaDB 中,数据保存为 float(8.2)。我收到此错误:

ArticlePrice 类的对象无法在 [file online...] 中转换为 int 格式

$item->addChild('price', $article->getPrice(CountryPublic::getByShortCut('a')));
$item->addChild('newPrice', $productPriceNew*1.8);

然后我尝试将它转换为 float(而不是 minifloat),如下所示:

$productPrice = $article->getUsualPrice(CountryPublic::getByShortCut('a'));
$productPriceNew = (float)$productPrice*1.8; 

我得到的信息是这样的:

ArticlePrice 类的对象无法转换为双精度

我做错了什么?

【问题讨论】:

  • $productPriceNew = (float)$productPrice*1.8; 行之前写var_dump($productPrice) 输出是什么?
  • 哪一行出现这个错误?
  • 看起来您的 getPricegetUsualPrice 方法返回类对象,而不是数字。您的ArticlePrice 班级是否有方法将价格作为数字获取?你需要调用它。
  • ArticlePrice 不是一个标准的 PHP 类,我们只能猜测它是如何工作的。
  • 总是最后一行 $productPriceNew 得到错误

标签: php oop floating-point type-conversion int


【解决方案1】:

您实际上是在尝试将一个对象转换为浮点数。

$article->getUsualPrice(CountryPublic::getByShortCut('a'));

您的方法getUsualPrice 返回一个对象ArticlePrice,您应该在您的类ArticlePrice 上放置一个getter 以访问其中的属性price,然后将其转换为浮点数。

这是最直接的解决方案,但在构思方面可能不是最漂亮的。

如果你尝试类似

var_dump($article->getUsualPrice(CountryPublic::getByShortCut('a')) instanceof ArticlePrice)

您看到您将一个对象投射到浮动中。

在你的评论之后

object(ArticlePrice)#11396 (15) { 
    ["id":protected]=> string(36) "7f01d63a-3f08-480a-b798-c83f6ddbdb94" 
    ["articleID":protected]=> string(36) "65983c99-66e4-43689ba7039dc5e742c0" 
    ["countryID":protected]=> string(36) "31149178-8a2a-4e57-8133-ca12004a59dd" 
    ["price":protected]=> string(5) "13.50"

你看到你得到了一个叫做价格的属性。

您只需要对该属性进行操作,而不是您的对象。 你的班级可能有一个叫做 getPrice() 的 getter。

以下代码将起作用:

(float)$article->getPrice(CountryPublic::getByShortCut('a'))->getPrice()

但是您可能需要花点时间考虑一下您的方法的名称,有两个称为getPrice()的方法是多余的

【讨论】:

  • 谢谢,但我该怎么做呢?
  • $article->getUsualPrice(CountryPublic::getByShortCut('a')) 返回对象 ArticlePrice。向您的对象ArticlePrice 添加一个新方法,例如getAmount(),它返回包含价格的属性。所以你可以写类似(float)$article->getUsualPrice(CountryPublic::getByShortCut('a'))->getAmount()
猜你喜欢
  • 1970-01-01
  • 2018-12-16
  • 1970-01-01
  • 2020-10-11
  • 2021-06-06
  • 2017-03-19
  • 1970-01-01
  • 1970-01-01
  • 2017-12-09
相关资源
最近更新 更多