Inheritance is a wonderful feature of OOPS. It is solved the duplication of code.
Code duplication happened when user
In Inheritance, there have
Child class has the power to access all or a few methods and variables of the parent class. Child class has also own member variables or functions.
Child class has the power to access all or few methods and variables of the
How to extend Parent or Base Class
name = $name;
return "My name is " .$this->name;
}
}
class Dog extends Animal {
}
$dog = new Dog;
echo $dog->Greet(“Bob”);
?>
Output
My name is Bob
Parent Class: A class which is inherited from another class that is called parent or base or superclass.
Child Class: A class which is inherits from another class that is called child or sub or derived class.
In this above
Dog class can access Animal class member variable and function for Inheritance. Extends keyword helps to create
Whenever wants to inherit parent class then need to use extends keyword to create child class.
Child class cannot access all properties of parent class. In PHP there are 3 types of Access Specifiers.
Public: By
All public members of parent class can, by child class and also out of the uses. Public member
Private: Private member defines by Private Keyword. Only Parent class can be accessed Private property.
Private property cannot be access in child class and out of the class.
Protected: Protected Member defines by Protected Keyword. Protected Members are only access into Parent Class and its child class.
Protected property cannot access out of the class.
Example
public; echo $this->protected; echo $this->private; } } $obj = new SimpleClass(); echo $obj->public; // Works echo "
"; echo $obj->protected; // Fatal Error: Cannot access protected property SimpleClass::$protected echo $obj->private; // Fatal Error: Cannot access private property SimpleClass::$private $obj->showme(); // Shows Public, Protected and Private echo "
"; class SimpleClass2 extends SimpleClass { //can be redeclare the public and protected properties, but not private public $public = 'Public2'; protected $protected = 'Protected2'; function describe() { echo $this->public; echo $this->protected; echo $this->private; } } $obj2 = new SimpleClass2(); echo $obj2->public; // Works echo "
"; echo $obj2->protected; // Fatal Error: Cannot access protected property SimpleClass2::$protected echo $obj2->private; // Undefined $obj2->describe(); // Shows Public2, Protected2, Undefined echo "
"; ?>
Five Types of Inheritance in Programming Language:
- Single Inheritance
- Multiple Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Hybrid Inheritance
But in PHP only Single and Multi-level inheritance supported.
- Single Inheritance: There only one base class and one child class. Child class only derived from one base class.
Example:
- Multi-Level Inheritance: There one base class derived one child class and that child class derived another child class and so on.
Example