HomePHP OOPSPHP OOPs Inheritance – Full Explanation

PHP OOPs Inheritance – Full Explanation

Inheritance is one of the key features of Object-Oriented Programming (OOP) in PHP. It allows a class (child class) to inherit properties and methods from another class (parent class). This promotes code reusability and a hierarchical class structure.

πŸ”Ή What is Inheritance?

Inheritance allows us to create a new class from an existing class. The new class (child class) inherits all the public and protected properties and methods of the parent class.

Syntax

phpCopyEditclass ParentClass {
    // Properties & Methods
}

class ChildClass extends ParentClass {
    // Additional Properties & Methods
}

πŸ“ Note: A child class cannot inherit private properties and methods of a parent class.


πŸ”Ή Types of Inheritance in PHP

PHP supports single-level inheritance and multilevel inheritance but does not support multiple inheritance (i.e., a class cannot inherit from more than one class directly).

1️⃣ Single-Level Inheritance

A single child class extends a parent class.

Example:

class Animal {
    public function sound() {
        echo "Animals make sounds!";
    }
}

class Dog extends Animal {
    public function bark() {
        echo "Dog barks!";
    }
}

$dog = new Dog();
$dog->sound(); // Output: Animals make sounds!
$dog->bark();  // Output: Dog barks!

2️⃣ Multilevel Inheritance

A child class extends another child class.

Example:

class GrandParent {
    public function familyName() {
        echo "Smith Family";
    }
}

class ParentClass extends GrandParent {
    public function parentMethod() {
        echo "Parent Method Called";
    }
}

class ChildClass extends ParentClass {
    public function childMethod() {
        echo "Child Method Called";
    }
}

$obj = new ChildClass();
$obj->familyName();   // Output: Smith Family
$obj->parentMethod(); // Output: Parent Method Called
$obj->childMethod();  // Output: Child Method Called

πŸ”Ή Using protected Access Modifier

  • protected properties and methods cannot be accessed directly outside the class.
  • They can be accessed inside the child class.

Example:

class Car {
    protected $brand = "Toyota";

    protected function getBrand() {
        return $this->brand;
    }
}

class Model extends Car {
    public function showBrand() {
        return $this->getBrand();
    }
}

$model = new Model();
echo $model->showBrand(); // Output: Toyota

πŸ”Ή Overriding Methods in Child Class

A child class can redefine a method inherited from the parent class. This is called method overriding.

Example:

class ParentClass {
    public function show() {
        echo "Hello from Parent Class!";
    }
}

class ChildClass extends ParentClass {
    public function show() {
        echo "Hello from Child Class!";
    }
}

$obj = new ChildClass();
$obj->show(); // Output: Hello from Child Class!

πŸ“ Note: If a method is overridden in the child class, it replaces the parent method.


πŸ”Ή Calling Parent Class Method using parent::

To access the parent class method inside the child class, use the parent:: keyword.

Example:

class ParentClass {
    public function message() {
        echo "Hello from Parent!";
    }
}

class ChildClass extends ParentClass {
    public function message() {
        parent::message(); // Call Parent Method
        echo " Hello from Child!";
    }
}

$obj = new ChildClass();
$obj->message(); 
// Output: Hello from Parent! Hello from Child

πŸ”Ή Constructor in Inheritance

A child class can also inherit a constructor from the parent class. If both the parent and child classes have constructors, the child class constructor will override the parent’s constructor.

Example:

class ParentClass {
    public function __construct() {
        echo "Parent Constructor Called\n";
    }
}

class ChildClass extends ParentClass {
    public function __construct() {
        parent::__construct(); // Call Parent Constructor
        echo "Child Constructor Called";
    }
}

$obj = new ChildClass();
// Output:
// Parent Constructor Called
// Child Constructor Called

πŸ”Ή Preventing Inheritance using final Keyword

If you don’t want a class to be inherited, use the final keyword.

Example:

final class FinalClass {
    public function show() {
        echo "Cannot be inherited";
    }
}

// class ChildClass extends FinalClass {} // ❌ Error: Cannot extend final class

Similarly, you can prevent method overriding by using final on methods.

class ParentClass {
    final public function show() {
        echo "Cannot be overridden";
    }
}

class ChildClass extends ParentClass {
    // public function show() {} // ❌ Error: Cannot override final method
}

πŸ”Ή Abstract Class and Inheritance

Abstract classes cannot be instantiated and must be inherited.

Example:

abstract class Animal {
    abstract public function makeSound();
}

class Dog extends Animal {
    public function makeSound() {
        echo "Woof! Woof!";
    }
}

$dog = new Dog();
$dog->makeSound(); // Output: Woof! Woof!

πŸ“ Note: Any child class must define the abstract method of the parent class.


πŸ”Ή Interfaces and Multiple Inheritance Alternative

PHP does not support multiple inheritance, but you can achieve it using interfaces.

Example:

interface A {
    public function methodA();
}

interface B {
    public function methodB();
}

class C implements A, B {
    public function methodA() {
        echo "Method A\n";
    }

    public function methodB() {
        echo "Method B";
    }
}

$obj = new C();
$obj->methodA(); // Output: Method A
$obj->methodB(); // Output: Method B

Can constructors be inherited in PHP?

Yes, but if the child class defines its own constructor, it overrides the parent’s constructor. To call the parent constructor, use parent::__construct().

Can a child class override parent methods in PHP?

Yes. A child class can override parent methods, and can also call the overridden method using parent::methodName().

What is the role of final keyword in inheritance?

A final class cannot be extended.
A final method cannot be overridden by child classes.

What is the difference between private, protected, and public in inheritance?

public: Accessible everywhere.
protected: Accessible within the class and its children.
private: Accessible only within the defining class.

Can a child class access private members of the parent class?

No. Only protected and public members are accessible to child classes.

What are traits and how do they help with inheritance limitations in PHP?

Traits allow you to reuse methods across multiple classes without using inheritance.

What happens if the child class has a method with the same name as the parent class method?

The child method overrides the parent method. You can still access the parent method using parent::methodName().

Can static methods be inherited?

Yes, static methods are inherited and can be accessed using self::, parent::, or class name.

How does late static binding work in PHP inheritance?

Late static binding allows a static method to be called based on the runtime class. It uses static:: instead of self::.

What happens if a child class does not call parent::__construct()?

The parent constructor won’t be executed unless explicitly called.

Can interfaces be inherited in PHP?

Yes, a class can implement one or more interfaces, and interfaces themselves can extend other interfaces.

πŸ”Ή Conclusion

Inheritance in PHP is a powerful feature that allows: βœ… Code Reusability
βœ… Method Overriding
βœ… Hierarchical Class Structure
βœ… Encapsulation using protected
βœ… Use of parent:: to call parent methods

Would you like a video tutorial or need help with a real-world example? πŸš€

Share:Β 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *