In php, we can check if a property exists in a class or an object with the built-in php property_exists() function.
class exampleClass {
public $id;
private $name;
static protected $multiplyNumbers;
static function multiplyNumbers($a,$b) {
return $a * $b;
}
}
var_dump(property_exists('exampleClass', 'name'));
var_dump(property_exists(new exampleClass, 'name'));
var_dump(property_exists('exampleClass', 'multiplyNumbers'));
var_dump(property_exists('exampleClass', 'other'));
// Output:
bool(true)
bool(true)
bool(true)
bool(false)
When working with objects in our php programs, it is useful to be able to check if an object has a certain property or not.
We can check if an object has a particular property in php with the php property_exists() function.
Below are some examples of using property_exists() in php to check if a property exists in a php object.
class exampleClass {
public $id;
private $name;
static protected $multiplyNumbers;
static function multiplyNumbers($a,$b) {
return $a * $b;
}
}
var_dump(property_exists('exampleClass', 'name'));
var_dump(property_exists(new exampleClass, 'name'));
var_dump(property_exists('exampleClass', 'multiplyNumbers'));
var_dump(property_exists('exampleClass', 'other'));
// Output:
bool(true)
bool(true)
bool(true)
bool(false)
Checking if a Property Exists in php Object with Exception Handling
Another way you can check if a property exists in a php object is with exception handling.
When you try to access a property and the property doesn’t exist, then you will get an error. If you don’t get an error, you know the property is there.
Therefore, using this logic, we can check if a property exists in an object.
Below is an example in php of checking if different properties exist using exception handling.
class exampleClass {
public $id;
private $name;
static protected $multiplyNumbers;
static function multiplyNumbers($a,$b) {
return $a * $b;
}
}
try {
exampleClass::doSomething();
}
catch(Error | Exception $e) {
echo "n Exception Caught: ", $e->getMessage();
}
try {
exampleClass::multiplyNumbers(2,3);
echo "n This works!";
}
catch(Error | Exception $e) {
echo "n Exception Caught: ", $e->getMessage();
}
//Output:
Exception Caught: Call to undefined method exampleClass::doSomething()
This works!
Hopefully this article has been useful for you to learn how to check if an object has an property or not in php.