0

I am wondering if there is in php7.3/php7.4 somehow possible to check inline if and object exists and if yes then get it's property like nullsafe operator. Like this it returns error:

$object = null;
echo $object->property;

But like this it is ok but still too long for me.

$object = ['property' => 'success'];   
echo $object->property;

I would like to see something like in Javascript object?.property but this does not work:

//$object = ['property' => 'success'];   
echo $object?->property;
  • You would need to use PHP 8+ for the last example. (https://stackoverflow.com/questions/12351737/is-there-a-nullsafe-operator-in-php) – Nigel Ren Dec 22 '22 at 11:13
  • Just use the [null coalescing operator](https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op) – mark_b Dec 22 '22 at 12:23

1 Answers1

0

You can try the following code to check if it is an object and it has a specific property.

$property = ( is_object($object) && isset($object->property) ) ? $object->property: "";