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,
    ];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?