douzi6060 2019-08-14 09:08
浏览 121
已采纳

PHP - 返回NULL的日期时间会引发错误

I am extracting some data from a db, but my DateTime field is causing issues.

If I set the DateTime field, it returns fine, but when I set it to NULL, it always throws an error.

My first code:

$results = $this->getMyRepository()->findAll();

$rows = [];

$rows[] = array(
    "id",
    "created"
);

foreach ($results as $row) {
    $rows[] = [
        $row->getId(),
        $row->getCreated(new \DateTime())->format('Y-m-d'),
    ];
}
return $rows;
}

Error:

Call member function format on null

My second changes the $row->getCreated() assignment:

$row->getCreated() ?? new \DateTime('now'))->format('Y-m-d');

This gives:

> Coalesce operator is available in PHP 7 only.

When I execute php -v it says PHP 7.2.19-0ubuntu0.18.04.1 on Symfony 3.4. and other syntax errors with this code.

Can someone help with synatax or tell me how to make datetime work on NULL?

  • 写回答

1条回答 默认 最新

  • douou8954 2019-08-14 09:48
    关注

    If PHP 7 runs on you machine you could do it like this:

    $row->getCreated() ?? (new \DateTime('now'))->format('Y-m-d');
    
    

    So with an extra ( before new \DateTime

    If you have to do it with lower PHP version

    $createdAt = $row->getCreatedAt();
    if (!$createdAt) {
        $now = new DateTime('now');
        $createdAt = $now->format('Y-m-d');
    }
    
    $rows[] = [
        $row->getId(),
       $createdAt,
    ];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求解答(matlab)
  • ¥30 ffmpeg库使用过程中遇到的问题
  • ¥15 pyqt5 中python如何通过Qtwebchannel主动发消息给web前端
  • ¥15 关于HTML中title获取xml内容的问题
  • ¥15 fanuc机器人PRIO083数字信号未复原错误,如何解决?
  • ¥20 如何为现有电路板增加远程控制功能
  • ¥15 C#点击按钮的时候的循环次数就是最后一次,如何是循环第几次的值?
  • ¥15 UE5打包失败,求解决
  • ¥15 请问STM32G431的CANOPEN协议函数怎么写
  • ¥15 graphpad prism 三因素重复测定报错