The property_exists() function is an inbuilt function in PHP that is used to check objects and classes have properties or not.
Syntax:
bool property_exists(object|string $object_or_class, string $property);
Parameters: This function accept two parameters that are described below:
- $object_or_class: The name of the class or object to test for the property.
- $property_name: This name of the property in the class.
Return Value: This function returns true if the property exists, and false if property doesn’t exist, and null in case of getting an error.
Example 1: In this example, we will check whether the property is in class or not by using the PHP property_exists() function in PHP.
PHP
<?php class My_Class_Property_Check { public $name ; private $empid ; protected $salary ; static function check_prop() { var_dump(property_exists( 'My_Class_Property_Check' , 'empid' )); } } // If the property exists it will be // return true otherwise false var_dump(property_exists( 'My_Class_Property_Check' , 'name' )); var_dump(property_exists( 'MY_Class_Property_Check' , 'salary' )); My_Class_Property_Check::check_prop(); ?> |
Output:
bool(true) bool(true) bool(true)
Example 2: In this example, we will check the property using the object of the class using PHP property_exists() method.
PHP
<?php class My_Class_Property_Check { public $name ; private $empid ; protected $salary ; static function check_prop() { var_dump(property_exists( new My_Class_Property_Check, 'empid' )); } } // If the property exists it will be // return true otherwise false var_dump(property_exists( new MY_Class_Property_Check, 'salary' )); // This property does not exists // so it will return false var_dump(property_exists( new MY_Class_Property_Check, 'net_salary' )); My_Class_Property_Check::check_prop(); ?> |
Output:
bool(true) bool(false) bool(true)
Reference: https://www.php.net/manual/en/function.property-exists.php