PHP check whether property exists in object or class

后端 未结 8 1532
情深已故
情深已故 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:34

    Neither isset or property_exists work for me.

    • isset returns false if the property exists but is NULL.
    • property_exists returns true if the property is part of the object's class definition, even if it has been unset.

    I ended up going with:

        $exists = array_key_exists($property, get_object_vars($obj));
    

    Example:

        class Foo {
            public $bar;
    
            function __construct() {
                $property = 'bar';
    
                isset($this->$property); // FALSE
                property_exists($this, $property); // TRUE
                array_key_exists($property, get_object_vars($this)); // TRUE
    
                unset($this->$property);
    
                isset($this->$property); // FALSE
                property_exists($this, $property); // TRUE
                array_key_exists($property, get_object_vars($this)); // FALSE
    
                $this->$property = 'baz';
    
                isset($this->$property); // TRUE
                property_exists($this, $property); // TRUE
                array_key_exists($property, get_object_vars($this));  // TRUE
            }
        }
    

提交回复
热议问题