【问题标题】:Casting string number to integer after __toString throws error__toString 后将字符串数字转换为整数会引发错误
【发布时间】:2021-08-06 01:15:49
【问题描述】:

我遇到了一个奇怪的问题,我做了一个类似的问题,您可以在下面看到它。
必须在类中有“__toString”方法,并且我不能修改读取它的方式(通过 __toString),因为它是框架的一部分。

class Integer{
    private $value = 2;
    
    **Must be implemented:**
    public function __toString(){
        return (string) $this->value;
    }
    
    public function asString(){
        return (string) $this->value;   
    }
}

$test = new Integer;

echo (int) $test->asString(); // 2
**Is used by framework:**
echo (int) $test; // Object of class Integer could not be converted to int

可以用它做点什么吗?为什么会这样?
提前谢谢,我不知道该怎么办。

更新:详情

我使用 ValueObject 作为 ID 参数(它现在的外观在this question 的答案中给出)。当我在获取的行上“加载”时,查询生成器会运行此代码(第 1020 行):

foreach ($values as &$value) {
    $value = (int) $value;
}

然后抛出该错误。我无法更改此代码。我认为我应该找到一种方法来更改我的 ValueObject,但我不知道如何以 Laravel 的方式进行。

【问题讨论】:

  • 您依赖于转换为 int 调用 __toString,这不会发生。我不明白问题是什么,您可以修改哪些代码,哪些不可以。不过看看这个related issue

标签: php laravel casting


【解决方案1】:

__toString 仅在您尝试将对象表示为字符串时调用 - 这里您尝试将其表示为 int。您需要先将其转换为字符串。

echo (int) (string) $test;

【讨论】:

  • 我更新了我的问题,请看。当我将 Laravel 核心代码更改为您的时,它可以工作,但我不能这样做。
猜你喜欢
  • 1970-01-01
  • 2019-10-16
  • 1970-01-01
  • 2018-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多