What is Inheritance in PHP?

What is Inheritance in PHP?

Category: Oop

 Inheritance in PHP allows a child class (also called a subclass) to inherit properties and methods from a parent class (also known as a superclass). This means you can define common functionality once and reuse it across multiple classes without rewriting code.

class ParentClass {

    public function greet() {

        echo "Hello from Parent!";

    }

}

 

class ChildClass extends ParentClass {

    // Inherits greet() method

}

 

$obj = new ChildClass();

$obj->greet();  // Output: Hello from Parent!

Here, ChildClass automatically has access to greet() from ParentClass because it uses the extends keyword.

  • What Are Interfaces in PHP? | PHP Interface Example & Benefits
  • What are interfaces in PHP, and how are they used?
  • What is Encapsulation in PHP?
  • How Do Classes and Objects Differ in PHP? [Explained with Example]
  • What Are the 4 Main Principles of Object-Oriented Programming (OOP)? [With Examples]