What are some best practices for handling method existence checks in PHP inheritance scenarios?
When working with PHP inheritance, it's important to handle method existence checks to avoid fatal errors when calling methods that may not exist in certain classes. One common approach is to use the method_exists() function to check if a method exists before calling it. This helps to ensure that the method is available in the current class or any of its parent classes.
class ParentClass {
public function parentMethod() {
if (method_exists($this, 'childMethod')) {
$this->childMethod();
} else {
echo "Child method does not exist.";
}
}
}
class ChildClass extends ParentClass {
public function childMethod() {
echo "Child method called.";
}
}
$childObj = new ChildClass();
$childObj->parentMethod(); // Output: Child method called.