我们使用以下代码,这些代码在php7.4上工作得很好,但是在php8.1上我们得到了一个不推荐的错误。但是,我们如何才能成功地为php8.1重写这些呢?
错误:
Deprecated Functionality: DateTime::__construct(): Passing null to parameter #1 ($datetime) of type string is deprecated当前代码:
$today = new \DateTime();$orderdate = new \DateTime($orders->getCreatedAt());
<?php if($orderdate->diff($today)->days > 14):?>
<?php endif;?>发布于 2022-09-19 10:30:29
你不能再这样做了:
new \DateTime(null);在您的确切用例中,我认为PHP在代码中突出了一个bug。如果订单没有创建的日期,您将使用脚本运行时的日期/时间填充变量,这可能不是您想要的:
var_dump(new \DateTime('1985-12-31 15:00:00'));
var_dump(new \DateTime(''));
var_dump(new \DateTime(null));object(DateTime)#1 (3) {
["date"]=>
string(26) "1985-12-31 15:00:00.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(16) "Europe/Amsterdam"
}
object(DateTime)#1 (3) {
["date"]=>
string(26) "2022-09-19 12:28:23.003960"
["timezone_type"]=>
int(3)
["timezone"]=>
string(16) "Europe/Amsterdam"
}
Deprecated: DateTime::__construct(): Passing null to parameter #1 ($datetime) of type string is deprecated in /in/67OFM on line 5
object(DateTime)#1 (3) {
["date"]=>
string(26) "2022-09-19 12:28:23.003987"
["timezone_type"]=>
int(3)
["timezone"]=>
string(16) "Europe/Amsterdam"
}如果您想使用DB信息:
$orderdate = $orders->getCreatedAt()
? new \DateTime($orders->getCreatedAt())
: null;如果您想默认为“现在”,请将其显示出来,这样就不会有人怀疑它是否是有意的:
$orderdate = $orders->getCreatedAt()
? new \DateTime($orders->getCreatedAt())
: new \DateTime();最后但同样重要的是..。从业务逻辑的角度分析没有创建日期的订单是否有意义。那是什么意思?
https://stackoverflow.com/questions/73770765
复制相似问题