Inheritance in PHP: A Simple Guide With Examples
PHP supports single inheritance. It improves your code structure, and you can use it to share methods and properties between classes.
Join the DZone community and get the full member experience.
Join For FreeUnderstand the Inheritance in PHP
Inheritance gives you the ability to use the code from another class. It helps reduce repetition and also makes your code organized.
When you create a parent class with common properties and methods, the child class extends it and gets access to that code. The child can also add its own features or override the parent’s methods.
Here is an example:
class Gibson {
public function run() {
echo "Running device";
}
}
class AirCondition extends Gibson {
public function run() {
echo "Cooling room";
}
}
$ac = new AirCondition();
$ac->run();
Output:
Cooling room
The AirCondition
class extends Gibson
. It overrides the run
method with its own version.
In the following part, you will learn more about the types of inheritance in PHP. Let's move on.
Types of Inheritance in PHP
We have three types, which are as follows:
- Single inheritance: One child class inherits from one parent.
- Multilevel inheritance: A class inherits from a class that already inherited from another class.
- Hierarchical inheritance: Multiple child classes inherit from the same parent class.
Here is an example:
class Device {
public function start() {
echo "Device started";
}
}
class Gibson extends Device {
public function run() {
echo "Running device";
}
}
class AirCondition extends Gibson {
public function cool() {
echo "Cooling room";
}
}
Here we have three classes with inheritance: Device
, Gibson
, and AirCondition
. Device
has a method start()
that outputs "Device started". Gibson
extends Device
and adds a run()
method, so objects of Gibson
can use both start()
and run()
. AirCondition
extends Gibson
, inheriting both start()
and run()
, and adds a cool()
method.
This creates a class multilevel inheritance, where AirCondition
can access all three methods: start()
, run()
, and cool()
.
Here is another example of hierarchical inheritance:
class Gibson {
public function run() {
echo "Running device";
}
}
class AirCondition extends Gibson {
public function cool() {
echo "Cooling room";
}
}
class Heater extends Gibson {
public function heat() {
echo "Warming room";
}
}
The Gibson
class has a run()
method. Both AirCondition
and Heater
extend Gibson
inheriting its run()
method. AirCondition
adds a cool()
method, while Heater
adds a heat()
method. This shows how child classes inherit and extend functionality from a parent class.
The Reasons for Using PHP Inheritance
So, why should you use inheritance in PHP?
- Inheritance allows child classes to reuse code from the parent class. That reduces redundancy and makes maintenance easier.
- It helps you organize code, group similar functionality in a parent class, and extend it in child classes.
- Child classes can override or extend methods from the parent class, offering customization without changing the base functionality.
- If a common feature needs an update, you can change it in the parent class, and all child classes will inherit the update automatically.
Now, let's understand how to override methods and how classes and objects use them.
Override Methods in PHP
Override methods can happen when a subclass provides a new implementation for a method already existing in the parent class. The child class method must have the same name and parameters. It also should have the same visibility.
Let's take an example:
class Device {
public function start() {
echo "Device started";
}
}
class AirCondition extends Device {
public function start() {
echo "AirCondition started";
}
}
$device = new AirCondition();
$device->start();
Output:
AirCondition started
Use the parent Keyword in PHP
The parent
keyword allows you to call methods or access properties from the parent class. It is useful when you override a method in a child class but still need to call the original method from the parent class.
class Device {
public function start() {
echo "Device started";
}
}
class AirCondition extends Device {
public function start() {
echo "AirCondition started. ";
parent::start(); // Call the parent class method
}
}
$device = new AirCondition();
$device->start();
Output:
AirCondition started. Device started.
Constructors are not inherited by default. The child class will inherit the parent's constructor if it does not define its own constructor.
However, the child class will override the parent constructor if it defines a constructor.
Use the parent::__construct()
method to call the parent's constructor from the child class:
class Device {
public function __construct() {
echo "Device constructor called\n";
}
}
class AirCondition extends Device {
public function __construct() {
parent::__construct(); // Call parent constructor
echo "AirCondition constructor called\n";
}
}
$device = new AirCondition();
Output:
Device constructor called
AirCondition constructor called
Here is how it works:
AirCondition
overrides the parent constructor, but it still callsDevice
's constructor usingparent::__construct()
.- This makes sure that both constructors are executed when it creates an
AirCondition
object.
Single vs. Multilevel Inheritance in PHP
Single inheritance means a class inherits from one parent. Multilevel inheritance means a class inherits from a child class that already inherited from another class.
Single Inheritance Example
class Country {
public function capital() {
echo "The capital city of this country.";
}
}
class Japan extends Country {
public function language() {
echo "The language spoken is Japanese.";
}
}
Japan
inherits the capital()
method from Country
.
Multilevel Inheritance Example
class Country {
public function capital() {
echo "The capital city of this country.";
}
}
class Asia extends Country {
public function continent() {
echo "This country is in Asia.";
}
}
class Japan extends Asia {
public function language() {
echo "The language spoken is Japanese.";
}
}
The Japan
class inherits from Asia
, which inherits from Country
. So, Japan
can access the methods capital()
, continent()
, and language()
.
Inheritance vs. Interfaces in PHP
The inheritance in PHP lets a class take code from one parent class. The child gets methods and properties from the parent and can change them. PHP allows one parent only.
While the interfaces define rules a class must follow. They don’t contain code, just method names. A class must write its own code for each method. PHP allows a class to use many interfaces.
Here is an example:
interface Speak {
public function speak();
}
class Japan implements Speak {
public function speak() {
echo "Japan speaks Japanese.";
}
}
- Inheritance shares actual code.
- The PHP Interfaces force classes to follow a structure.
Inheritance and Access Modifiers in PHP
The access modifiers in PHP control the visibility of methods and properties. They affect how inheritance works, which restricts or allows access to certain parts of a class. The three main access modifiers are:
- The "public" keyword determines that methods and properties are accessible from anywhere. It includes child classes.
- The "protected" keyword shows you that methods and properties are accessible within the class and its subclasses but not from outside.
- The "private" refers to methods and properties that are only accessible within the class they are defined in, not in subclasses or from outside.
Here is an example:
class Device {
public $name;
protected $brand;
private $serialNumber;
public function __construct($name, $brand, $serialNumber) {
$this->name = $name;
$this->brand = $brand;
$this->serialNumber = $serialNumber;
}
public function getName() {
return $this->name;
}
protected function getBrand() {
return $this->brand;
}
private function getSerialNumber() {
return $this->serialNumber;
}
}
class AirCondition extends Device {
public function displayInfo() {
//=> public method
echo $this->getName();
//=> protected method can be accessed by subclass
echo $this->getBrand();
//=> This shows error: private method can't be accessed in subclass
// echo $this->getSerialNumber();
}
}
$ac = new AirCondition("Cooler", "Samsung", "12345");
$ac->displayInfo();
- Public properties or methods (like
name
andgetName()
) can be accessed anywhere. - Protected properties or methods (like
brand
andgetBrand()
) are accessible within the class and child classes, but not outside. - Private properties or methods (like
serialNumber
andgetSerialNumber()
) can only be accessed inside the class where they are defined.
Conclusion
Inheritance lets you reuse code. You write shared features in a parent class. Then, child classes use them. That doesn't require you to repeat the code.
A child class can also add new methods or replace ones from the parent. That gives you control. You saw how single, multilevel, and hierarchical inheritance work. Each type shows how one class can build on another.
You also learned how to override methods. If a method exists in both parent and child, PHP runs the child’s version. But you can still call the parent’s version with the parent
keyword.
Thank you for reading!
Opinions expressed by DZone contributors are their own.
Comments