Abstract Class in PHP
Abstract Class & Method in PHP
Recall, a class in which a method cannot be implemented or a developer cannot provide definition. The object oriented language provide the concept of defining abstract method. The class having an abstract method is to be defined as an abstract class.
PHP like Java and C#.NET also provides abstract keyword to defined an abstract method as well as an abstract class. Now in PHP, the two-dimensional figure class is implemented as follows:
abstract class TwoDFigure
{
protected $d1;
protected $d2;
public function __construct($d1,$d2)
{
$this->d1 = $d1;
$this->d2 = $d2;
}
// Force Extending class to define this method
abstract protected function computeArea();
}
The abstract class can only be used by inheriting it. However, its object cannot be created i.e. cannot be instantiated. Recall, Inheritance represents a IS_A relationship. Therefore, a Triangle is a two-dimensional figure, a Rectangle is also a two-dimensional figure. The following code demonstrate how to use the abstract class.
class Rectangle extends TwoDFigure
{
public function __construct($length, $breadth)
{
parent::__construct($length,$breadth);
}
public function computeArea()
{
$area = $this->d1 * $this->d2;
echo "
Area of Rectangle ".$area;
}
}
class Triangle extends TwoDFigure
{
public function __construct($base, $height)
{
parent::__construct($base,$height);
}
public function computeArea()
{
$area = (1.0/2.0) *($this->d1 * $this->d2);
echo "
Area of Triangle ".$area;
}
}
Recall, in PHP the reference of the super class can refer to the objects of the sub classes and then it calls the method of that class. It is used to achieve runtime polymorphism.
The Rectangle and the Triangle class can be tested by the following code is used the test the above defined classes.
$figure = new Rectangle(10,20);
$figure->computeArea();
$figure = new Triangle(10,20);
$figure->computeArea();
The abstract method is a unimplemented method in an abstract class. It is provided implementation in the respective sub classes. It archives runtime Polymorphism.
Recall, PHP is a Server-Side Scripting language, To test the above code, a PHP based Web Page is to be created.
Imagine the cut-copy and the paste operation in software. Their implementation varies from one software to another software.
Abstract Class in PHP
Reviewed by Syed Hafiz Choudhary
on
September 15, 2023
Rating:
No comments: