Extending classes lets you create a new class based on an existing one. This helps you reuse code and add new features easily.
0
0
Extending classes in PHP
Introduction
When you want a new class to have all features of an existing class plus some extra.
When you want to organize similar things in a family of classes.
When you want to change or add behavior without rewriting code.
When you want to keep your code clean and avoid repetition.
Syntax
PHP
<?php class ParentClass { // properties and methods } class ChildClass extends ParentClass { // new or changed properties and methods } ?>
The extends keyword is used to create a child class.
The child class inherits all public and protected properties and methods from the parent.
Examples
This example shows a child class
Dog that changes the speak method of the parent Animal.PHP
<?php class Animal { public function speak() { echo "Animal sound\n"; } } class Dog extends Animal { public function speak() { echo "Bark!\n"; } } $dog = new Dog(); $dog->speak(); ?>
The
Car class extends Vehicle and adds a new method openDoor.PHP
<?php class Vehicle { public function start() { echo "Vehicle started\n"; } } class Car extends Vehicle { public function openDoor() { echo "Door opened\n"; } } $car = new Car(); $car->start(); $car->openDoor(); ?>
Sample Program
This program shows a Student class extending Person. The student has a name and a grade. It can greet and study.
PHP
<?php class Person { public $name; public function __construct($name) { $this->name = $name; } public function greet() { echo "Hello, my name is {$this->name}.\n"; } } class Student extends Person { public $grade; public function __construct($name, $grade) { parent::__construct($name); $this->grade = $grade; } public function study() { echo "{$this->name} is studying for grade {$this->grade}.\n"; } } $student = new Student("Alice", 10); $student->greet(); $student->study(); ?>
OutputSuccess
Important Notes
Use parent::__construct() to call the parent class constructor inside the child.
Child classes can override parent methods by defining a method with the same name.
Only public and protected members are inherited; private members are not accessible directly.
Summary
Extending classes helps reuse and organize code by creating child classes from parent classes.
Use extends keyword to make a child class inherit from a parent.
Child classes can add new features or change existing ones easily.