HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

PHP OOP - Inheritance

In PHP Object-Oriented Programming (OOP), inheritance allows a class to inherit properties and methods from another class, called the parent or superclass. This enables code reuse and the creation of hierarchical relationships between classes.


Here's how inheritance works in PHP:

Example

// Parent class
class ParentClass {
    // Properties
    public $property1;
    protected $property2;
    private $property3;
    
    // Constructor
    public function __construct($prop1, $prop2, $prop3) {
        $this->property1 = $prop1;
        $this->property2 = $prop2;
        $this->property3 = $prop3;
    }
    
    // Method
    public function method1() {
        echo "Method 1 from ParentClass\n";
    }
    
    protected function method2() {
        echo "Method 2 from ParentClass\n";
    }
    
    private function method3() {
        echo "Method 3 from ParentClass\n";
    }
}

// Child class
class ChildClass extends ParentClass {
    // Additional property
    public $extraProperty;
    
    // Constructor
    public function __construct($prop1, $prop2, $prop3, $extraProp) {
        // Call parent class constructor
        parent::__construct($prop1, $prop2, $prop3);
        $this->extraProperty = $extraProp;
    }
    
    // Method overriding
    public function method1() {
        echo "Method 1 from ChildClass\n";
    }
    
    // Method added only to ChildClass
    public function newMethod() {
        echo "New method added to ChildClass\n";
    }
}

// Create an object of the ChildClass
$obj = new ChildClass("Value 1", "Value 2", "Value 3", "Extra Value");

// Access properties and methods
echo $obj->property1 . "\n"; // Accessing inherited property
//$obj->property2; // Cannot access protected property from outside
//$obj->property3; // Cannot access private property from outside
$obj->method1(); // Call overridden method
//$obj->method2(); // Cannot access protected method from outside
//$obj->method3(); // Cannot access private method from outside
$obj->newMethod(); // Call method specific to ChildClass

You can click on above box to edit the code and run again.

Output