Inheritance is a fundamental concept in object-oriented programming (OOP), including PHP. It allows you to create a new class (a child or derived class) based on an existing class (a parent or base class). Inheritance enables the child class to inherit properties (attributes) and methods (functions) from the parent class while also allowing for customization or extension of its behavior. Hereand#39;s how to use inheritance in PHP:
Create a Parent (Base) Class:
andnbsp;
phpCopy code
class Animal { public $name; public function __construct($name) { $this-andgt;name = $name; } public function speak() { echo andquot;Animal speaks.andquot;; } }
Create Child Classes:
extends
keyword followed by the name of the parent class.andnbsp;
phpCopy code
class Dog extends Animal { public function speak() { echo andquot;Dog barks.andquot;; } } class Cat extends Animal { public function speak() { echo andquot;Cat meows.andquot;; } }
Instantiate Child Objects:
andnbsp;
phpCopy code
$dog = new Dog(andquot;Rexandquot;); $cat = new Cat(andquot;Whiskersandquot;);
Access Parent Methods and Properties:
parent::
keyword.andnbsp;
phpCopy code
$dog-andgt;speak(); // Outputs: Dog barks. $cat-andgt;speak(); // Outputs: Cat meows.
Override Methods (Optional):
andnbsp;
phpCopy code
class Dog extends Animal { public function speak() { echo andquot;Dog barks.andquot;; } public function fetch() { echo andquot;Dog fetches a ball.andquot;; } }
Use the parent
Keyword (Optional):
parent
keyword.andnbsp;
phpCopy code
class Dog extends Animal { public function speak() { parent::speak(); // Calls the parent classand#39;s speak method. echo andquot;Dog barks.andquot;; } }
Inheritance allows you to create a hierarchy of classes where child classes inherit and extend the functionality of parent classes. It promotes code reusability and helps you model real-world relationships effectively in your PHP applications.