首页 > 解决方案 > DateTime::setTime() 期望参数 1 为 int,给定字符串,但在尝试观察时消失

问题描述

我在 php7.4 中有以下代码,用于从另一个创建日期

    $date = clone $regularCourse->getNextCronExecutionDate();
    $date->modify('+ 3 days');
    $date->setTime($date->format('H'), $date->format('i'), 0, 0);

我已经在本地和生产环境中对其进行了测试,它曾经可以正常工作。突然间它开始失败了。有错误

DateTime::setTime() expects parameter 1 to be int, string given

它经常失败并且可以预见地失败,因为我的哨兵给了我 4000 次事件的发生(这是一个每分钟运行一次的 cron 任务,哨兵告诉我错误在过去几天每小时发生 60 次)

但 !

现在我已经添加了一些调试以显示该值,它不再失败我使用的代码

     // Added to debug some courses failing
     ob_start();
     var_dump($date);
     $dumped_message= ob_get_clean();

     \Sentry\addBreadcrumb(
         new \Sentry\Breadcrumb(
             \Sentry\Breadcrumb::LEVEL_INFO,
             \Sentry\Breadcrumb::TYPE_DEFAULT,
             'error_reporting',
             "course Id " . $regularCourse->getId()
         )
     );
     \Sentry\addBreadcrumb(
         new \Sentry\Breadcrumb(
             \Sentry\Breadcrumb::LEVEL_INFO,
             \Sentry\Breadcrumb::TYPE_DEFAULT,
             'error_reporting',
             $dumped_message
         )
     );

我不知道 var_dump-ing 变量是否会产生一些副作用?

所以我的问题

  1. 这个错误什么时候发生?
  2. 为什么我的调试代码使问题消失?

标签: phpdatetime

解决方案


如果你使用declare(strict_types=1)你需要注意类型:

  • DateTime::setTime()需要整数:

    public DateTime::setTime ( int $hour , int $minute [, int $second = 0 [, int $microseconds = 0 ]] ) : DateTime
    
  • DateTime::format()返回字符串:

    public DateTime::format ( string $format ) : string
    

在这种情况下,您可以只转换为 int,尽管这很容易掩盖其他格式错误:

declare(strict_types=1);
$date = new \DateTime();
// Correct
$date->setTime((int)$date->format('H'), (int)$date->format('i'), 0, 0);
// Typo, no error thrown becuase `Sunday` casts to 0
$date->setTime((int)$date->format('l'), (int)$date->format('i'), 0, 0);

... 尽管

$date = new \DateTime();
$date->setTime($date->format('l'), $date->format('i'), 0, 0);
// DateTime::setTime() expects parameter 1 to be int, string given

推荐阅读