How can a child class in PHP access and override a method from its parent class?
To access and override a method from its parent class, a child class in PHP can simply declare a method with the same name as the parent class method. This is known as method overriding. By doing this, the child class can provide its own implementation of the method while still being able to access the parent class method using the `parent::` keyword.
class ParentClass {
public function methodToOverride() {
echo "Parent class method";
}
}
class ChildClass extends ParentClass {
public function methodToOverride() {
parent::methodToOverride(); // Accessing parent class method
echo "Child class method";
}
}
$child = new ChildClass();
$child->methodToOverride();
Keywords
Related Questions
- What are some best practices for structuring PHP code to handle different sections of a website effectively?
- What is the error message "Unable to find the wrapper 'https' - did you forget to enable it when you configured PHP" indicating in PHP usage?
- What are the potential issues with attempting to delete a directory using PHP, particularly in relation to file permissions and access rights?