Inheritance

Last updated on

Ever felt like you’re rewriting the same logic over and over in your PHP classes? Maybe it’s the same properties or methods that just keep popping up. Here's where PHP inheritance steps in to avoid that.

With inheritance, you can set up shared behaviors in one place—so your code is more streamlined, less repetitive, and, most importantly, easier to manage.

In the next sections, you will learn how PHP inheritance can help you write cleaner, simpler code without all the repetition.

What is PHP Inheritance?

Generally, inheritance is a way for one class to gain the properties and methods of another. So if you have a class called Vehicle with properties like $wheels and $engine. Instead of creating a Car class and retyping those same properties, you can set up Vehicle as a parent class. Then, Car can inherit all that useful info directly from Vehicle without duplicating code.

This lets you define shared traits in one place, saving you from repeating yourself and keeping things organized.

Inheritance creates a structure where the parent class holds common traits, while child classes use and expand upon those traits as needed.

In the following example, you will learn how to write inheritance in PHP:

class ParentClass {
    public $property;

    public function method() {
        // Code here
    }
}

class ChildClass extends ParentClass {
    // Additional properties or methods specific to ChildClass
}

In this setup:

  • ParentClass defines common properties and methods.
  • ChildClass inherits from ParentClass and gets access to all public and protected methods and properties.

The “extends” keyword is the key to inheritance, telling PHP that ChildClass should inherit everything in ParentClass.

Anyway, In the below section, you’ll see how to set up inheritance in PHP.

Setting Up Inheritance in PHP

Consider you are creating a system that manages different kinds of vehicles. You might start with a Vehicle class:

class Vehicle {
    protected $wheels;
    protected $engine;

    public function __construct($wheels, $engine) {
        $this->wheels = $wheels;
        $this->engine = $engine;
    }

    public function startEngine() {
        return "Engine started";
    }
}

Now, if you want to create specific vehicle types like Car or Bike, these classes can be inherited from Vehicle:

class Car extends Vehicle {
    public function drive() {
        return "Car is driving with " . $this->wheels . " wheels.";
    }
}

class Bike extends Vehicle {
    public function pedal() {
        return "Bike is pedaling with " . $this->wheels . " wheels.";
    }
}

So, Car and Bike inherit the properties $wheels and $engine, as well as the startEngine() method from Vehicle. This structure is tidy, prevents repetitive code, and allows each class to add its unique traits.

You are now seeing how inheritance can simplify your code and improve the code readability. In the following section, you will learn the types of inheritance in PHP and which one you have to use.

Types of PHP Inheritance and Which One Do You Need?

PHP primarily supports single inheritance. This means a class can inherit from only one parent class, which can sometimes feel limiting. But don’t worry—PHP offers two ways to work around this if you need more flexibility:

  1. Single Inheritance: As the name suggests, each class can have only one parent class. So, Car can inherit from Vehicle but not from multiple classes.
  2. Interfaces: If you need a class to follow multiple “rules” without forcing a strict hierarchy, interfaces are doing that. An interface lets you define specific methods a class must implement, allowing a class to take on several behaviors.
  3. Traits: For times when you want to share methods across classes but don’t want strict inheritance, PHP offers traits. Traits let you add methods to multiple classes without creating a formal parent-child relationship. They’re handy for sharing functionality without locking classes into a hierarchy.

Each of these options provides a way to tailor your code structure based on what you are trying to achieve.

In the next section, let’s bring it all together with some examples.

Example of PHP Inheritance

Here, we can take our Vehicle example and expand it to show how inheritance plays together.

class Vehicle {
    protected $engine;
    public function startEngine() {
        return "Starting engine...";
    }
}

class Car extends Vehicle {
    public function honk() {
        return "Honk! Honk!";
    }
}

class Motorcycle extends Vehicle {
    public function revEngine() {
        return "Revving engine!";
    }
}

In this example, the Car and Motorcycle both inherit from Vehicle, but each adds something unique—honk() for Car and revEngine() for Motorcycle. This way, you maintain shared functionality in Vehicle, while each child class focuses on its specific behavior.

Anyway, let's summarize it.

Wrapping Up

PHP inheritance lets you share common properties and methods across different classes, saving you time and simplifying your code. Here is a quick summary of the basics:

  • Parent Class: The main class that holds shared traits.
  • Child Class: Inherits from the parent class and can add or override methods.
  • Single Inheritance: PHP only allows one parent class per child class, but you can use traits and interfaces for flexibility.
  • Syntax: Use extends to set up inheritance, and define unique methods in child classes.

If you need to read more PHP tutorials, click here. Thank you for reading.

Frequently Asked Questions (FAQs)

  • What is 'PHP inheritance'?

    PHP inheritance lets one class inherit properties and methods from another class, reducing repetition and organizing shared behaviors in one place.
  • How do you set up inheritance in PHP?

    Use the extends keyword to set a child class that inherits from a parent class. Example:
    class ParentClass {
        public $property;
        public function method() {
            // Code here
        }
    }
    
    class ChildClass extends ParentClass {
        // Additional properties or methods specific to ChildClass
    }
  • What are the benefits of inheritance in PHP?

    Inheritance allows you to set up shared traits in a parent class, saving time and reducing repetitive code across similar classes.
  • Can a child class in PHP have more than one parent class?

    No, PHP only supports single inheritance, meaning a class can inherit from one parent class. For multiple behaviors, use interfaces or traits.
  • What is single inheritance in PHP?

    Single inheritance means each class can inherit from only one parent class. This keeps class hierarchies simple and structured.
  • What are interfaces and traits, and how do they work with inheritance?

    Interfaces set method requirements without a strict hierarchy, while traits allow you to share methods across classes without formal inheritance. Both offer flexibility beyond single inheritance.
  • What is an example of PHP inheritance with a parent and child class?

    Here’s a basic setup using a Vehicle class with Car and Motorcycle as children:
    class Vehicle {
        protected $engine;
        public function startEngine() {
            return "Starting engine...";
        }
    }
    
    class Car extends Vehicle {
        public function honk() {
            return "Honk! Honk!";
        }
    }
    
    class Motorcycle extends Vehicle {
        public function revEngine() {
            return "Revving engine!";
        }
    }
    
    $car = new Car();
    echo $car->startEngine(); // Outputs: Starting engine...
    echo $car->honk(); // Outputs: Honk! Honk!
    
    $motorcycle = new Motorcycle();
    echo $motorcycle->startEngine(); // Outputs: Starting engine...
    echo $motorcycle->revEngine(); // Outputs: Revving engine!
  • How does inheritance help with code readability in PHP?

    Inheritance reduces repetitive code, so shared methods are only defined once in the parent class, making the code more organized and easier to follow.
  • Can child classes override methods from a parent class in PHP?

    Yes, child classes can override inherited methods to provide specific functionality. This allows customization while maintaining shared behavior from the parent class.
  • How do traits add functionality without inheritance?

    Traits allow you to add methods across classes without setting up a parent-child relationship, offering a way to share functionality without strict inheritance.
Share on: