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?
property_exists( mixed $class , string $property )
if (property_exists($ob, 'a'))
isset( mixed $var [, mixed $... ] )
NOTE : Mind that isset() will return false if property is null
if (isset($ob->a))
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
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
}