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.

Share:
15,179
Narek
Author by

Narek

Updated on June 14, 2022

Comments

  • Narek
    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
    Narek almost 11 years
    Thanks, didn't know about null.