PHP check whether property exists in object or class

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

    Just putting my 2 cents here.

    Given the following class:

    class Foo
    {
      private $data;
    
      public function __construct(array $data)
      {
        $this->data = $data;
      }
    
      public function __get($name)
      {
        return $data[$name];
      }
    
      public function __isset($name)
      {
        return array_key_exists($name, $this->data);
      }
    }
    

    the following will happen:

    $foo = new Foo(['key' => 'value', 'bar' => null]);
    
    var_dump(property_exists($foo, 'key'));  // false
    var_dump(isset($foo->key));  // true
    var_dump(property_exists($foo, 'bar'));  // false
    var_dump(isset($foo->bar));  // true, although $data['bar'] == null
    

    Hope this will help anyone

提交回复
热议问题