PHP is an object-oriented programming language that supports inheritance. Inheritance is a mechanism that allows a class to inherit properties and methods from another class. In PHP, inheritance is implemented using the extends
keyword.
When a class extends another class, it inherits all the properties and methods of the parent class. The child class can also override the properties and methods of the parent class or add new properties and methods.
Let's take a look at an example:
class Animal {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function eat() {
echo $this->name . " is eating.";
}
}
class Dog extends Animal {
public function bark() {
echo $this->name . " is barking.";
}
}
$dog = new Dog("Max");
$dog->eat(); // Output: Max is eating.
$dog->bark(); // Output: Max is barking.
In the example above, we have two classes: Animal
and Dog
. The Dog
class extends the Animal
class using the extends
keyword. This means that the Dog
class inherits all the properties and methods of the Animal
class.
We create a new instance of the Dog
class and pass in the name "Max" to the constructor. We then call the eat()
method, which is inherited from the Animal
class, and the bark()
method, which is defined in the Dog
class.
We can also override the properties and methods of the parent class in the child class. Let's take a look at another example:
class Animal {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function eat() {
echo $this->name . " is eating.";
}
}
class Dog extends Animal {
public function bark() {
echo $this->name . " is barking.";
}
public function eat() {
echo $this->name . " is eating loudly.";
}
}
$dog = new Dog("Max");
$dog->eat(); // Output: Max is eating loudly.
$dog->bark(); // Output: Max is barking.
In this example, we have overridden the eat()
method in the Dog
class. When we call the eat()
method on the dog
object, it will output "Max is eating loudly." instead of "Max is eating."
PHP inheritance is a powerful feature that allows us to reuse code and create more efficient and maintainable applications. By using inheritance, we can create a hierarchy of classes that share common properties and methods, and we can easily extend and modify these classes as needed.
PHP inheritance is a powerful feature that allows us to create a hierarchy of classes that share common properties and methods. By using inheritance, we can easily reuse code and create more efficient and maintainable applications.