image

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:

  1. Create a Parent (Base) Class:
    • Begin by defining the parent class (also known as the base or superclass). This class contains the properties and methods that you want to share with the child classes.
    
    andnbsp;
    phpCopy code class Animal { public $name; public function __construct($name) { $this-name = $name; } public function speak() { echo Animal speaks.; } }
  2. Create Child Classes:
    • Next, create one or more child classes that inherit from the parent class. Child classes are defined using the extends keyword followed by the name of the parent class.
    
    andnbsp;
    phpCopy code class Dog extends Animal { public function speak() { echo Dog barks.; } } class Cat extends Animal { public function speak() { echo Cat meows.; } }
  3. Instantiate Child Objects:
    • You can now create objects (instances) of the child classes. These objects inherit properties and methods from the parent class.
    
    andnbsp;
    phpCopy code $dog = new Dog(Rex); $cat = new Cat(Whiskers);
  4. Access Parent Methods and Properties:
    • Child objects have access to both the methods and properties of the parent class. You can call parent methods using the parent:: keyword.
    
    andnbsp;
    phpCopy code $dog-speak(); // Outputs: Dog barks. $cat-speak(); // Outputs: Cat meows.
  5. Override Methods (Optional):
    • Child classes can override parent methods to provide their own implementation. This allows child classes to customize behavior while maintaining the same method name.
    
    andnbsp;
    phpCopy code class Dog extends Animal { public function speak() { echo Dog barks.; } public function fetch() { echo Dog fetches a ball.; } }
  6. Use the parent Keyword (Optional):
    • When overriding methods in child classes, you can still access the parent classand#39;s version of the method using the parent keyword.
    
    andnbsp;
    phpCopy code class Dog extends Animal { public function speak() { parent::speak(); // Calls the parent classand#39;s speak method. echo Dog barks.; } }
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.