Method overriding and overloading are two important concepts in object-oriented programming (OOP) that involve the modification or extension of methods inherited from parent classes. Let’s explain each concept with examples:
// Parent class
class Animal {
public function makeSound() {
return "Generic animal sound";
}
}
// Child class inheriting from Animal
class Dog extends Animal {
public function makeSound() {
return "Woof! Woof!";
}
}
// Creating instances of both classes
$animal = new Animal();
$dog = new Dog();
// Calling makeSound() method of each object
echo $animal->makeSound(); // Output: Generic animal sound
echo $dog->makeSound(); // Output: Woof! Woof!
Explanation:
Dog
class overrides the makeSound()
method inherited from the Animal
class with its implementation ("Woof! Woof!"
).makeSound()
method on a Dog
object, it returns the overridden implementation specific to dogs.class Calculator {
// Method with default parameter values
public function add($a, $b = 0) {
return $a + $b;
}
// Method with variable-length argument list
public function multiply(...$numbers) {
$result = 1;
foreach ($numbers as $number) {
$result *= $number;
}
return $result;
}
}
// Creating an instance of the Calculator class
$calculator = new Calculator();
// Calling add() method with one or two arguments
echo $calculator->add(5); // Output: 5
echo $calculator->add(2, 3); // Output: 5
// Calling multiply() method with different numbers of arguments
echo $calculator->multiply(2, 3, 4); // Output: 24
echo $calculator->multiply(5, 10, 2); // Output: 100
Explanation:
Calculator
the class has two methods named add()
and multiply()
.add()
the method has a default parameter value ($b = 0
), so it can be called with one or two arguments.multiply()
method uses a variable-length argument list (denoted by ...$numbers
), allowing it to accept any number of arguments.While PHP does not directly support method overloading as in some other languages, you can achieve similar functionality using default parameter values or variable-length argument lists to provide flexibility in method invocation.
Leave A Comment