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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With