Home > Software engineering >  How to detect null default value for non-typed class property via reflection in PHP?
How to detect null default value for non-typed class property via reflection in PHP?

Time:10-03

When using reflection (ReflectionClass), is it possible to detect, whether a non-typed class property has a null default value specified, or has no default value at all?

class A {
    public $foo;
    public $bar = null;
}

Here, for both foo and bar, the ReflectionProperty::getDefaultValue() returns null and ReflectionProperty::hasDefaultValue() returns true.

$rc = new ReflectionClass(A::class);
var_dump($rc->getProperty("foo")->hasDefaultValue()); // true
var_dump($rc->getProperty("foo")->getDefaultValue()); // null
var_dump($rc->getProperty("bar")->hasDefaultValue()); // true
var_dump($rc->getProperty("bar")->getDefaultValue()); // null

How can I differentiate between the two properties?

CodePudding user response:

get_object_vars() should allow to make the difference

The documentation https://www.php.net/manual/en/function.get-object-vars.php says

Uninitialized properties are considered inaccessible, and thus will not be included in the array.

CodePudding user response:

Since php 7.4, class properties have an uninitialized state. This state is not the same as null:

class A {
    public string $foo;
}

$a = new A();
var_dump($a->foo === null);

Fatal error: Uncaught Error: Typed property A::$foo must not be accessed before initialization in ...

However, if there is no type declared the property will have null as its uninitialized value:

class B {
    public $foo;
}

$b = new B();
var_dump($b->foo === null); // true

You can use ReflectionProperty::isInitialized to check whether a property is initialized and ReflectionProperty::hasType to check if it has a type.

  • Related