PHP check whether property exists in object or class

后端 未结 8 1540
情深已故
情深已故 2020-12-02 11:01

I understand PHP does not have a pure object variable, but I want to check whether a property is in the given object or class.

$ob = (object) array(\'a\' =&g         


        
8条回答
  •  囚心锁ツ
    2020-12-02 11:11

    property_exists( mixed $class , string $property )

    if (property_exists($ob, 'a')) 
    

    isset( mixed $var [, mixed $... ] )

    if (isset($ob->a))
    

    isset() will return false if property is null

    Example 1:

    $ob->a = null
    var_dump(isset($ob->a)); // false
    

    Example 2:

    class Foo
    {
       public $bar = null;
    }
    
    $foo = new Foo();
    
    var_dump(property_exists($foo, 'bar')); // true
    var_dump(isset($foo->bar)); // false
    

提交回复
热议问题