Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

iFelix's avatar

PHP: avoid "Accessing property of a non object (null)"

Hi all!

I've got a simple question regarding PHP and not Laravel only. In my code I often have statements like if($booking->guest->first_name == 'John') which throws a notice if guest is not defined. Of course if guest is not defined the guest is not John. What's the best way to avoid this notice? Of course I could do something like

if(!is_null($booking->guest)) {
    if($booking->guest->first_name == 'John') {}
}

But I really don't like this syntax which is too long. What would be recommended in that case?

Many thanks,

Felix

0 likes
2 replies
ChristopherSFSD's avatar
Level 4
if ($booking->guest && $booking->guest->first_name == 'John') {}
iFelix's avatar

I like it, wasn't sure if PHP read the second condition before executing the 1st one. If anyone has other suggestions please do not hesitate :)

Please or to participate in this conversation.