PHP check whether property exists in object or class PHP check whether property exists in object or class php php

PHP check whether property exists in object or class


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 = nullvar_dump(isset($ob->a)); // false

Example 2:

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


To check if the property exists and if it's null too, you can use the function property_exists().

Docs: http://php.net/manual/en/function.property-exists.php

As opposed with isset(), property_exists() returns TRUE even if the property has the value NULL.

bool property_exists ( mixed $class , string $property )

Example:

if (property_exists($testObject, $property)) {    //do something}


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        }    }