Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 880
Heiko Jerichen Avatar asked Dec 05 '25 17:12

Heiko Jerichen


1 Answers

It is discouraged to do this, see the conversation below this rejected pull request for implementing an is_initialized native PHP function.

But if really needed it can be done using the ReflectionProperty::isInitialized method.

like image 81
Attila Fulop Avatar answered Dec 07 '25 21:12

Attila Fulop



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!