Unit - 3 Apply Object Oriented Concepts in PHP
Unit - 3 Apply Object Oriented Concepts in PHP
// destructor
function __destruct()
{
// clearing the object reference
}
}
?>
Single Inheritance
In a single inheritance, there is only one base class and one sub or derived class. It
directly inherits the subclass from the base class.
<?php
//PHP program to demonstrate the single inheritance.
class Base
{
function BaseFun()
{
echo "BaseFun() called<br>";
}
}
class Derived extends Base
{
function DerivedFun()
{
echo "DerivedFun() called<br>";
}
}
$dObj = new Derived();
$dObj->BaseFun();
$dObj->DerivedFun();
?>
Output
BaseFun() called
DerivedFun() called
Multi-Level Inheritance
In the multi-level inheritance, we will inherit the one base class into a derived class, and
then the derived class will become the base class for another derived class. <?php
//PHP program to demonstrate the multi-level inheritance.
class Base
{
function BaseFun()
{
echo "BaseFun() called<br>";
}
}
class Derived1 extends Base
{
function Derived1Fun()
{
echo "Derived1Fun() called<br>";
}
}
class Derived2 extends Derived1
{
function Derived2Fun()
{
echo "Derived2Fun() called<br>";
}
}
$dObj = new Derived2();
$dObj->BaseFun();
$dObj->Derived1Fun();
$dObj->Derived2Fun();
?>
Output
BaseFun() called
Derived1Fun() called
Derived2Fun() called
Hierarchical Inheritance
In the hierarchical inheritance, we will inherit the one base class into multiple
derived classes.
<?php
//PHP program to demonstrate the hierarchical inheritance.
class Base
{
function BaseFun()
{
echo "BaseFun() called<br>";
}
}
$Obj1->BaseFun();
$Obj1->Derived1Fun();
echo "<br>";
$Obj2->BaseFun();
$Obj2->Derived2Fun();
Output
BaseFun() called
?> Derived1Fun() called
BaseFun() called
Derived2Fun() called
Multiple Inheritance(Using interface)
Multiple inheritance is a type of inheritance in which one class can inherit the
properties from more than one parent class.
<?php
//PHP program to implement multiple-inheritance using the
interface.
class Base
{
public function Fun1()
{
printf("Fun1() called<br>");
}
}
interface Inf
{
public function Fun2();
}
class Derived extends Base implements Inf
{
function Fun2()
{
printf("Fun2() called<br>");
}
function Fun3()
{
printf("Fun3() called<br>");
}
}
$obj->Fun1();
$obj->Fun2();
$obj->Fun3();
Output
?> Fun1() called
Fun2() called
Fun3() called
Create a class as “Percentage” with two properties length & width. Calculate area of
rectangle for two objects.