Introduction
Inheritance helps us reuse code and organize related things easily. It lets one class get features from another without rewriting them.
Inheritance helps us reuse code and organize related things easily. It lets one class get features from another without rewriting them.
<?php class ParentClass { // common properties and methods } class ChildClass extends ParentClass { // additional properties and methods } ?>
extends keyword is used to inherit from a parent class.<?php class Animal { public function eat() { echo "Eating food\n"; } } class Dog extends Animal { public function bark() { echo "Barking\n"; } } $dog = new Dog(); $dog->eat(); $dog->bark(); ?>
<?php class Vehicle { public function start() { echo "Starting vehicle\n"; } } class Car extends Vehicle { public function honk() { echo "Honking horn\n"; } } $car = new Car(); $car->start(); $car->honk(); ?>
This program shows a Student class inheriting greet() from Person and adding study(). It prints greetings and study message.
<?php class Person { public function greet() { echo "Hello!\n"; } } class Student extends Person { public function study() { echo "Studying hard\n"; } } $student = new Student(); $student->greet(); $student->study(); ?>
Inheritance helps keep code DRY (Don't Repeat Yourself).
Only public and protected members are inherited, private ones are not.
Use inheritance to model "is-a" relationships, like Student is a Person.
Inheritance lets one class reuse code from another.
It helps organize related classes in a clear way.
It makes code easier to maintain and extend.
Car inherit from class Vehicle in PHP?extends is used to inherit from another class.extends correctly to inherit from Vehicle.class Animal {
public function sound() {
return "Some sound";
}
}
class Dog extends Animal {
public function sound() {
return "Bark";
}
}
$dog = new Dog();
echo $dog->sound();Dog class inherits from Animal but overrides the sound() method to return "Bark".$dog->sound(), the overridden method in Dog runs, returning "Bark".class ParentClass {
public function greet() {
return "Hello";
}
}
class ChildClass ParentClass {
public function greet() {
return "Hi";
}
}extends before the parent class name.extends in class ChildClass ParentClass, causing a syntax error.Employee with a method getDetails(). You want to create a Manager class that adds a new method getTeamSize() but still uses getDetails() from Employee. How should you use inheritance to achieve this?getDetails() from Employee, Manager should inherit from Employee.Manager can add its own method getTeamSize() without rewriting getDetails().Pass the test and this pattern moves unknown