Tommy J
Tommy J

Reputation: 109

PHP - Returning datetime of NULL throws error

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?

Upvotes: 1

Views: 280

Answers (1)

Paul
Paul

Reputation: 329

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,
];

Upvotes: 2

Related Questions