PHP OOP - Inheritance

In PHP (and many object-oriented programming languages), inheritance is a fundamental concept of Object-Oriented Programming (OOP) that allows a class (called a child or subclass) to inherit properties and methods from another class (called a parent or superclass). This promotes code reuse and modularity.

Basic Syntax

class ParentClass {
public $name;
public function sayHello() { echo "Hello from Parent";
} }
class ChildClass extends ParentClass { public function sayHelloChild() { echo "Hello from Child"; } } $child = new ChildClass();
$child->sayHello();
// Inherited from ParentClass $child->sayHelloChild();
// Defined in ChildClass

Key Concepts

  • extends: Used to declare that one class inherits from another.

  • The child class inherits all public and protected members of the parent class.

  • Private members of the parent are not accessible in the child.

  • You can override methods in the child class.

Method Overriding

class ParentClass
{ public function greet() { echo "Hi from Parent"; } }
class ChildClass extends ParentClass { public function greet()
{ echo "Hi from Child"; } }
$obj = new ChildClass();
$obj->greet(); // Outputs: Hi from Child

Using parent:: Keyword

To access the parent class’s method inside the child:

class ChildClass extends ParentClass { public function greet()
{ parent::greet();
// Calls ParentClass greet echo " and Child"; } }