How to use ineritence in php ?
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:
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.
andnbsp;
phpCopy code
class Animal { public $name; public function __construct($name) { $this-name = $name; } public function speak() { echo Animal speaks.; } }
andnbsp;
phpCopy code
class Dog extends Animal { public function speak() { echo Dog barks.; } } class Cat extends Animal { public function speak() { echo Cat meows.; } }
andnbsp;
phpCopy code
$dog = new Dog(Rex); $cat = new Cat(Whiskers);
andnbsp;
phpCopy code
$dog-speak(); // Outputs: Dog barks. $cat-speak(); // Outputs: Cat meows.
andnbsp;
phpCopy code
class Dog extends Animal { public function speak() { echo Dog barks.; } public function fetch() { echo Dog fetches a ball.; } }
andnbsp;
phpCopy code
class Dog extends Animal { public function speak() { parent::speak(); // Calls the parent classand#39;s speak method. echo Dog barks.; } }