How can property_exists be used to check for the existence of properties in PHP?
To check for the existence of properties in PHP, you can use the property_exists function. This function takes two parameters: the object or class name and the property name to check. It returns true if the property exists in the object or class, and false otherwise. This can be useful when you need to dynamically access properties and want to ensure they exist before trying to use them.
class MyClass {
public $name = 'John';
private $age = 30;
}
$obj = new MyClass();
if (property_exists($obj, 'name')) {
echo 'Property "name" exists in MyClass.';
} else {
echo 'Property "name" does not exist in MyClass.';
}