PHP - Inheritance: A Beginner's Guide

Hello there, future PHP wizards! Today, we're going to embark on an exciting journey into the world of PHP inheritance. Don't worry if you're new to programming – I'll be your friendly guide, explaining everything step by step. So, grab a cup of coffee (or tea, if that's your thing), and let's dive in!

PHP - Inheritance

What is Inheritance?

Inheritance is like a family tree for classes in PHP. Just as you might inherit your grandmother's eyes or your father's sense of humor, in programming, a class can inherit properties and methods from another class. This concept helps us write more organized and reusable code.

Think of it this way: imagine you're creating a video game with different types of characters. All characters might share some basic traits (like having a name or health points), but each type of character (like warriors or mages) might have unique abilities. Inheritance allows us to define these common traits in a base class and then create specific character classes that inherit these traits and add their own unique features.

Basic Inheritance Example

Let's start with a simple example to see how inheritance works in PHP.

class Animal {
    public $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function speak() {
        echo "The animal makes a sound.";
    }
}

class Dog extends Animal {
    public function speak() {
        echo $this->name . " barks: Woof woof!";
    }
}

$myDog = new Dog("Buddy");
$myDog->speak(); // Output: Buddy barks: Woof woof!

In this example, we have two classes: Animal and Dog. The Dog class extends the Animal class, which means it inherits all the properties and methods of Animal.

Let's break it down:

  1. We define a base Animal class with a $name property and a speak() method.
  2. We create a Dog class that extends Animal using the extends keyword.
  3. The Dog class overrides the speak() method with its own implementation.
  4. We create a new Dog object named "Buddy" and call its speak() method.

The Dog class inherits the $name property from Animal, but provides its own version of the speak() method. This is called method overriding, and it's a powerful feature of inheritance.

Inheritance and Access Modifiers

Now, let's talk about how inheritance works with different access modifiers (public, protected, and private).

class Vehicle {
    public $brand;
    protected $model;
    private $serialNumber;

    public function __construct($brand, $model, $serialNumber) {
        $this->brand = $brand;
        $this->model = $model;
        $this->serialNumber = $serialNumber;
    }

    public function getInfo() {
        return "Brand: " . $this->brand . ", Model: " . $this->model;
    }

    protected function getSerialNumber() {
        return $this->serialNumber;
    }
}

class Car extends Vehicle {
    public $doors;

    public function __construct($brand, $model, $serialNumber, $doors) {
        parent::__construct($brand, $model, $serialNumber);
        $this->doors = $doors;
    }

    public function getFullInfo() {
        return $this->getInfo() . ", Doors: " . $this->doors . ", SN: " . $this->getSerialNumber();
    }
}

$myCar = new Car("Toyota", "Corolla", "ABC123", 4);
echo $myCar->getFullInfo();
// Output: Brand: Toyota, Model: Corolla, Doors: 4, SN: ABC123

In this example:

  1. The Vehicle class has properties with different access modifiers.
  2. The Car class extends Vehicle and adds its own property ($doors).
  3. The Car class can access public and protected members of Vehicle, but not private members.
  4. We use parent::__construct() to call the parent class's constructor.

Remember:

  • Public members are accessible from anywhere.
  • Protected members are accessible within the class and its subclasses.
  • Private members are only accessible within the class they're defined in.

Constructor in Inheritance

Let's dive deeper into how constructors work in inheritance:

class Shape {
    protected $color;

    public function __construct($color) {
        $this->color = $color;
        echo "Shape constructor called.<br>";
    }
}

class Circle extends Shape {
    private $radius;

    public function __construct($color, $radius) {
        parent::__construct($color);
        $this->radius = $radius;
        echo "Circle constructor called.<br>";
    }

    public function getInfo() {
        return "A {$this->color} circle with radius {$this->radius}";
    }
}

$myCircle = new Circle("red", 5);
echo $myCircle->getInfo();

Output:

Shape constructor called.
Circle constructor called.
A red circle with radius 5

Here's what's happening:

  1. When we create a Circle object, PHP first calls the Shape constructor (the parent class).
  2. Then it calls the Circle constructor.
  3. We use parent::__construct($color) to ensure the Shape constructor is called and the $color property is set.
  4. Finally, we set the $radius property specific to the Circle class.

This ensures that both the parent and child classes are properly initialized.

Methods Reference Table

Here's a handy table of the methods we've used in our examples:

Method Description
__construct() Constructor method, called when an object is created
speak() Method to make an animal speak
getInfo() Method to get basic information about a vehicle
getSerialNumber() Protected method to get a vehicle's serial number
getFullInfo() Method to get complete information about a car

Conclusion

Inheritance is a powerful tool in PHP that allows us to create hierarchies of classes, promoting code reuse and organization. Remember, it's like building with LEGO blocks – you start with a base piece and keep adding more specific pieces on top.

As you continue your PHP journey, you'll find many more exciting ways to use inheritance. Keep practicing, and soon you'll be creating complex and efficient object-oriented programs with ease!

Happy coding, future PHP masters! ??‍??‍?

Credits: Image by storyset