Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting Undefined property: stdClass:: with PHP8 when using the nullsafe operator before an undeclared property?

Php 8.0 introduced the nullsafe operator which can be used like so $foo?->bar?->baz;. I have a code sample running on php 8.1 that throws the error Undefined property: stdClass::$first_name even though it is using the nullsafe operator:

$reference = (object) $reference; // Cast of array to object

return [
    'FirstName' => $reference?->first_name,
];

To solve the error, I have to use the null coalescing operator:

$reference = (object) $reference; // Cast of array to object

return [
    'FirstName' => $reference->first_name ?? null,
];

Why is the nullsafe operator throwing an error in this case?

like image 890
naghal Avatar asked Jan 01 '26 19:01

naghal


2 Answers

You seem to have a slight misunderstanding of what the nullsafe operator does.

If $reference was null, then $reference?->first_name would return null with no warning, but since $reference is actually an object, ?-> just functions like a normal object operator, hence the undefined property warning.

like image 174
Don't Panic Avatar answered Jan 03 '26 10:01

Don't Panic


You can use a try-catch in case you have many nested properties:

try {
    if ($response->foo->bar->foo->bar->status == 'something') {
        ...
    }
} catch (\ErrorException $ex) {
    // Property missing exception will be caught here
}
like image 23
the_nuts Avatar answered Jan 03 '26 10:01

the_nuts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!