Check if variable isset in object
15,179
Solution 1
Because
$foo = null;
var_dump(isset($foo)); // false
Maybe you want check it with property_exists or ReflectionClass::hasProperty
Solution 2
You should use a combination of both isset
and property_exists
:
if (property_exists($obj,$foo) && isset($obj->$foo)) {
// use $obj->foo
}
A property may exist with nothing set into it, which won't be accessible as expected.
Author by
Narek
Updated on June 14, 2022Comments
-
Narek almost 2 years
I have object:
class Obj { public $foo; public $bar; } $obj = new Obj(); print_R($obj);
Output:
Obj Object ( [foo] => [bar] => )
But
var_dump(isset($obj->foo));
output
bool(false)
.How to check is variable set in object?
-
Narek almost 11 yearsThanks, didn't know about
null
.