To inherit a base class by super class in PHP, you use the extends
keyword. For example, the following code shows how to inherit the Animal
class by the Dog
class:
PHP
class Animal {
protected $name;
public function __construct($name) {
$this-andgt;name = $name;
}
public function getName() {
return $this-andgt;name;
}
}
class Dog extends Animal {
public function bark() {
echo andquot;Woof!andquot;;
}
}
Use code with caution.andnbsp;Learn more
content_copy
The Dog
class now inherits all of the properties and methods of the Animal
class. This means that a Dog
object can access the name
property and call the getName()
method of the Animal
class.
In addition, the Dog
class can also override any of the properties and methods of the Animal
class. For example, the following code shows how to override the getName()
method of the Animal
class to return a different value:
PHP
class Dog extends Animal {
public function getName() {
return andquot;My dogand#39;s name is andquot; . $this-andgt;name;
}
}
Use code with caution.andnbsp;Learn more
content_copy
Now, when a Dog
object calls the getName()
method, it will return the string andquot;My dogand#39;s name is andquot; followed by the name of the dog.
Inheritance is a powerful feature of PHP that allows you to reuse code and create more complex and specialized classes.
Here are some additional things to keep in mind about inheritance in PHP: