I have this following piece of code in php7.4 , to create a date from an other
$date = clone $regularCourse->getNextCronExecutionDate(); $date->modify('+ 3 days'); $date->setTime($date->format('H'), $date->format('i'), 0, 0);
I’ve tested it locally and in production, and it used to work fine. And suddenly it started to fail. with the error
DateTime::setTime() expects parameter 1 to be int, string given
and it failed rather regularly and predictably because my sentry gave me 4000 occurence of the event (it’s a cron task that runs every minutes, and sentry show me the error has happened 60 times every hours for the last days)
BUT !
Now that i’ve added some debug in order to display the value, it does not fail anymore The code I’ve used
// Added to debug some courses failing ob_start(); var_dump($date); $dumped_message= ob_get_clean(); SentryaddBreadcrumb( new SentryBreadcrumb( SentryBreadcrumb::LEVEL_INFO, SentryBreadcrumb::TYPE_DEFAULT, 'error_reporting', "course Id " . $regularCourse->getId() ) ); SentryaddBreadcrumb( new SentryBreadcrumb( SentryBreadcrumb::LEVEL_INFO, SentryBreadcrumb::TYPE_DEFAULT, 'error_reporting', $dumped_message ) );
I don’t know if var_dump-ing the variable produce some side effect ?
so my questions
- when does this error happen ?
- why my debug code make the issue disapear ?
Advertisement
Answer
If you use declare(strict_types=1)
you need to be careful about types:
DateTime::setTime() expects integers:
public DateTime::setTime ( int $hour , int $minute [, int $second = 0 [, int $microseconds = 0 ]] ) : DateTime
DateTime::format() returns strings:
public DateTime::format ( string $format ) : string
In this case you can just cast to int, though that can easily mask other format errors:
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);
… while
$date = new DateTime(); $date->setTime($date->format('l'), $date->format('i'), 0, 0); // DateTime::setTime() expects parameter 1 to be int, string given