Inheritance
- A class can inherit the methods and properties of another class by using the keyword
extends
in the class declaration.
- It is not possible to extend multiple classes; a class can only inherit from one base class.
- The inherited methods and properties can be overridden by redeclaring them with the same name defined in the parent class. However, if the parent class has defined a method as final, that method may not be overridden. It is possible to access the overridden methods or static properties by referencing them with parent::.
<?php
class Car{
var $color = 'green';
public $price = 1000000;
private $engine = 'blah blah';
protected $no_of_wheels = 4 ;
function drive(){
echo 'driving...';
}
}
class TeslaCar extends Car {
public $manufacturer = 'Elon Musk';
function selfdrive(){
echo 'Self driving is also available along with driving';
}
}
$car_obj = new Car;
$my_tesla = new TeslaCar();
$my_tesla->drive();
$my_tesla->selfdrive();
echo 'Color : ' . $car_obj->color;
echo 'Price : ' . $car_obj->price;
?>
Method / Function Overriding
<?php
class Car{
var $color = 'green';
private $engine = 'blah blah';
public $price = 1000000;
protected $no_of_wheels = 4 ;
function drive(){
echo 'Engine : ' . $engine;
echo 'driving...';
}
}
class TeslaCar extends Car {
public $manufacturer = 'Elon Musk';
function drive(){
echo "Self Checking System.. Power ON <br>";
echo "Starting Audio <br>";
echo "driving...";
}
function selfdrive(){
echo 'Self driving is also available along with drive method';
}
}
?>