The property_exists Function
The property_exists function checks if the specified property exists in the given object or class. The first parameter accepts an object or a class name, and the second one - the name of the property to check. The function returns true if the property exists, and false otherwise.
Syntax
phpproperty_exists(object|string $object_or_class, string $property): bool
Example
Let's check for the existence of a property in an object:
php<?php
class MyClass {
public $prop1 = 'value';
}
$obj = new MyClass();
$res = property_exists($obj, 'prop1');
var_dump($res);
?>
Code execution result:
phptrue
Example
Let's check for the existence of a non-existent property:
php<?php
class MyClass {
public $prop1 = 'value';
}
$obj = new MyClass();
$res = property_exists($obj, 'prop2');
var_dump($res);
?>
Code execution result:
phpfalse
Example
Let's check for the existence of a property in a class (without creating an object):
php<?php
class MyClass {
public $prop1 = 'value';
}
$res = property_exists('MyClass', 'prop1');
var_dump($res);
?>
Code execution result:
phptrue
Example
Let's check for the existence of a protected property:
php<?php
class MyClass {
protected $prop1 = 'value';
}
$obj = new MyClass();
$res = property_exists($obj, 'prop1');
var_dump($res);
?>
Code execution result:
phptrue
See Also
-
the method_exists function,
which checks for the existence of a method -
the get_class_vars function,
which returns class properties -
the get_object_vars function,
which returns object properties