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

报告相同问题?

悬赏问题

  • ¥15 求C# .net4.8小报表工具
  • ¥15 安装虚拟机时出现问题
  • ¥15 Selenium+docker Chrome不能运行
  • ¥15 mac电脑,安装charles后无法正常抓包
  • ¥18 visio打开文件一直显示文件未找到
  • ¥15 请教一下,openwrt如何让同一usb储存设备拔插后设备符号不变?
  • ¥50 使用quartz框架进行分布式任务定时调度,启动了两个实例,但是只有一个实例参与调度,另外一个实例没有参与调度,不知道是为什么?请各位帮助看一下原因!!
  • ¥50 怎么获取Ace Editor中的python代码后怎么调用Skulpt执行代码
  • ¥30 fpga基于dds生成幅值相位频率和波形可调的容易信号发生器。
  • ¥15 R语言shiny包和ncdf4包报错