What is the difference between "overloading" and "overriding" methods in PHP?
Overloading in PHP refers to the ability to define multiple methods in a class with the same name but different parameters. Overriding, on the other hand, occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. Overloading allows for method polymorphism based on the number or type of parameters, while overriding enables a subclass to provide its own implementation of a method inherited from a superclass.
class ParentClass {
public function method($param) {
echo "Parent method with parameter: $param";
}
}
class ChildClass extends ParentClass {
public function method($param) {
echo "Child method with parameter: $param";
}
}
$parent = new ParentClass();
$parent->method("test"); // Output: Parent method with parameter: test
$child = new ChildClass();
$child->method("test"); // Output: Child method with parameter: test