Inheritance in php with example
Inheritance will derive all property and method of the parent class to the child class, with the ability to override the behavior
How to inherit a class
the child class can inherit from parent class using extends keywords. we will create File class as a parent and FileList as a child class.
<?php
class File
{
protected $name;
protected $type;
public function __construct($name,$type){
$this->name =$name;
$this->type =$type;
}
public function GeneratePath(){
return $this->name.'.'.$this->type;
}
}
class FileList extends File{
}
$FileList = new FileList('index','php');
How to Function Overriding
In a child's class, we can override the inherited method by redefining it. here we will rewrite the GeneratePath method
<?php
class File
{
protected $name;
protected $type;
public function __construct($name,$type){
$this->name =$name;
$this->type =$type;
}
public function GeneratePath(){
return $this->name.'.'.$this->type;
}
}
class FileList extends File{
public function GeneratePath(){
return 'qandeelacademy.com/'.$this->name.'.'.$this->type;
}
}
$FileList = new FileList('index','php');
echo $FileList->GeneratePath();