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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。