How can you extend a class in PHP to inherit methods from another class?
To extend a class in PHP and inherit methods from another class, you can use the `extends` keyword followed by the name of the class you want to inherit from. This allows the child class to access all the public and protected methods of the parent class. By extending a class, you can create a hierarchy of classes that share common functionality while allowing for customization and specialization in the child classes.
class ParentClass {
public function parentMethod() {
echo "This is a method from the parent class.";
}
}
class ChildClass extends ParentClass {
// ChildClass inherits the parentMethod from ParentClass
}
$child = new ChildClass();
$child->parentMethod(); // Output: This is a method from the parent class.
Related questions
-
Sanitize Validation htmlspecialchars
-
Xdebug PHP error reporting breakpoints
-
MySQL PHP simultaneous queries