Hi Im encountering fatal error on this and i cant find out any solutions here,
this is the error it returns when this function is called.
Fatal error: Uncaught Error: Call to a member function format() on null
$startDate = $data->started_at ? \DateTime::createFromFormat('Y-m-d H:i:s', $data->started_at) : null;
return $data ? (object) [
'planId' => $data->plan_id ?? '',
'comment' => $data->comment ?? '',
'facilitator' => $data->facilitator ?? '',
'date' => $startDate->format('d/m/Y') ?? '',
'time' => $startDate->format('H:i:s') ?? '',
] : (object) [];
}
additional Info,
I am trying to retrieve data on this, however in this case I have no startDate and still would like to return the data that was save. Im not sure if my syntax is right.
Thanks Lads
CodePudding user response:
Since $startDate
can sometimes be null, you need to check if it's null before calling format()
on it, since you can't call a method on a null value.
If you're using PHP 8.0, you can combine null-safe operators (?->
) with your existing null-coalescing operators (??
):
'date' => $startDate?->format('d/m/Y') ?? '',
'time' => $startDate?->format('H:i:s') ?? ''
Otherwise you can use ternary operators (? :
):
'date' => $startDate === null ? '' : $startDate->format('d/m/Y'),
'time' => $startDate === null ? '' : $startDate->format('H:i:s') ?? ''