17

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?

Allen M
  • 1,423
  • 9
  • 15
Heiko Jerichen
  • 171
  • 1
  • 5
  • 3
    I found a request for this on php.net: [link](https://bugs.php.net/bug.php?id=78480). It seems `ReflectionProperty::isInitialized` is the way to go for now. – Heiko Jerichen Feb 26 '21 at 10:03

2 Answers2

8

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.

Attila Fulop
  • 6,861
  • 2
  • 44
  • 50
2

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Tarik Weiss
  • 336
  • 2
  • 15