PHP Inheritance
Inheritance is a fundamental concept in object-oriented programming that allows a class to inherit properties and methods from another class. In PHP, a class can extend another class using the extends
keyword.
Benefits of Inheritance
- Code Reusability: Allows the reuse of existing code, reducing redundancy.
- Method Overriding: Subclasses can provide specific implementations of methods defined in the parent class.
- Improved Organization: Helps in organizing code into a hierarchical structure.
Example of Inheritance
<?php
class Animal {
public function speak() {
return "Animal speaks";
}
}
class Dog extends Animal {
public function speak() {
return "Dog barks";
}
}
$dog = new Dog();
echo $dog->speak(); // Outputs: Dog barks
?>
Output:
Dog barks
Explanation: In this example, the Dog
class inherits from the Animal
class. The speak
method is overridden in the Dog
class to provide a specific implementation. When the speak
method is called on a Dog
object, it outputs Dog barks.