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

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' => 1, 'b' => 12); 

or

$ob = new stdClass;
$ob->a = 1;
$ob->b = 2;

In JS, I can write this to check if variable a exists in an object:

if ('a' in ob)

In PHP, can anything like this be done?

Thank you very much for your advice.

This question is related to php class variables object parameters

The answer is


Using array_key_exists() on objects is Deprecated in php 7.4

Instead either isset() or property_exists() should be used

reference : php.net


To check if something exits, you can use the PHP function isset() see php.net. This function will check if the variable is set and is not NULL.

Example:

if(isset($obj->a))
{ 
  //do something
}

If you need to check if a property exists in a class, then you can use the build in function property_exists()

Example:

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

Solution

echo $person->middleName ?? 'Person does not have a middle name';

To show how this would look in an if statement for more clarity on how this is working.

if($person->middleName ?? false) {
    echo $person->middleName;
} else {
    echo 'Person does not have a middle name';
}

Explanation

The traditional PHP way to check for something's existence is to do:

if(isset($person->middleName)) {
    echo $person->middleName;
} else {
    echo 'Person does not have a middle name';
}

OR for a more class specific way:

if(property_exists($person, 'middleName')) {
    echo $person->middleName;
} else {
    echo 'Person does not have a middle name';
}

These are both fine in long form statements but in ternary statements they become unnecessarily cumbersome like so:

isset($person->middleName) ? echo $person->middleName : echo 'Person does not have a middle name';

You can also achieve this with just the ternary operator like so:

echo $person->middleName ?: 'Person does not have a middle name';

But... if the value does not exist (is not set) it will raise an E_NOTICE and is not best practise. If the value is null it will not raise the exception.

Therefore ternary operator to the rescue making this a neat little answer:

echo $person->middleName ?? 'Person does not have a middle name';


If you want to know if a property exists in an instance of a class that you have defined, simply combine property_exists() with isset().

public function hasProperty($property)
{
    return property_exists($this, $property) && isset($this->$property);
}

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

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


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
}

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to class

String method cannot be found in a main class method Class constructor type in typescript? ReactJS - Call One Component Method From Another Component How do I declare a model class in my Angular 2 component using TypeScript? When to use Interface and Model in TypeScript / Angular Swift Error: Editor placeholder in source file Declaring static constants in ES6 classes? Creating a static class with no instances In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric Static vs class functions/variables in Swift classes?

Examples related to variables

When to create variables (memory management) How to print a Groovy variable in Jenkins? What does ${} (dollar sign and curly braces) mean in a string in Javascript? How to access global variables How to initialize a variable of date type in java? How to define a variable in a Dockerfile? Why does foo = filter(...) return a <filter object>, not a list? How can I pass variable to ansible playbook in the command line? How do I use this JavaScript variable in HTML? Static vs class functions/variables in Swift classes?

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to parameters

Stored procedure with default parameters AngularJS ui router passing data between states without URL C#: HttpClient with POST parameters HTTP Request in Swift with POST method In Swift how to call method with parameters on GCD main thread? How to pass parameters to maven build using pom.xml? Default Values to Stored Procedure in Oracle How do you run a .exe with parameters using vba's shell()? How to set table name in dynamic SQL query? How to pass parameters or arguments into a gradle task