Check in PHP 7.4 whether a property is really initialized or not

Viewed 2357

I want to check in PHP 7.4 whether a property is really initialized or not. Setting the property to null means it is initialized with null.

I can not use isset because it returns false even when it is set to null.
I can not use property_exists because it returns true even when it is not initialized.

The only way I know is with ReflectionProperty::isInitialized, but that feels a little bit strange, that I need to use this detour.

class DTO {
    public ?string $something;
}

$object = new DTO();
$object->something = null;

isset($object->something); //returns false
is_initialized($object->something); //should return true;

I could write this function using ReflectionProperty, but maybe I'm missing something?

2 Answers

You could also try to catch the access with a Throwable. Because if it is strongly typed and is accessed before initialization, it throws an error.

Related