DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Becoming a Skilled PHP Developer: A Comprehensive Guide
  • A Guide to Constructor Chaining in Java
  • The Blue Elephant in the Room: Why PHP Should Not Be Ignored Now or Ever
  • Build Your Own Programming Language

Trending

  • Kubeflow: Driving Scalable and Intelligent Machine Learning Systems
  • Revolutionizing Financial Monitoring: Building a Team Dashboard With OpenObserve
  • It’s Not About Control — It’s About Collaboration Between Architecture and Security
  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  1. DZone
  2. Coding
  3. Languages
  4. Inheritance in PHP: A Simple Guide With Examples

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.

By 
Montasser Mossallem user avatar
Montasser Mossallem
·
Apr. 15, 25 · Tutorial
Likes (0)
Comment
Save
Tweet
Share
2.6K Views

Join the DZone community and get the full member experience.

Join For Free

Understand 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:

PHP
 
class Gibson {
  public function run() {
    echo "Running device";
  }
}

class AirCondition extends Gibson {
  public function run() {
    echo "Cooling room";
  }
}

$ac = new AirCondition();
$ac->run(); 


Output:

Plain Text
 
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:

PHP
 
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:

PHP
 
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:

PHP
 
class Device {
  public function start() {
    echo "Device started";
  }
}

class AirCondition extends Device {
  public function start() {
    echo "AirCondition started";
  }
}

$device = new AirCondition();
$device->start();  


Output:

Plain Text
 
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.

PHP
 
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:

Plain Text
 
 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:

PHP
 
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:

Plain Text
 
Device constructor called 

AirCondition constructor called 


Here is how it works:

  • AirCondition overrides the parent constructor, but it still calls Device's constructor using parent::__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

PHP
 
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

PHP
 
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:

PHP
 
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:

PHP
 
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 and getName()) can be accessed anywhere.
  • Protected properties or methods (like brand and getBrand()) are accessible within the class and child classes, but not outside.
  • Private properties or methods (like serialNumber and getSerialNumber()) 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!

PHP Inheritance (object-oriented programming) Language code

Opinions expressed by DZone contributors are their own.

Related

  • Becoming a Skilled PHP Developer: A Comprehensive Guide
  • A Guide to Constructor Chaining in Java
  • The Blue Elephant in the Room: Why PHP Should Not Be Ignored Now or Ever
  • Build Your Own Programming Language

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!