abstract method and abstract class
Summary: in this tutorial, you will learn about the PHP abstract class and abstract method, and learn how to use abstract class to define a framework for the class hierarchy.
Introduction to abstract method and abstract class
In an inheritance hierarchy, subclasses implement specific details, whereas the parent class defines the framework its subclasses. The parent class also serves a template for common methods that will be implemented by its subclasses. To make the parent classes more general and abstract, PHP provides abstract method and abstract class.
An abstract method is a method that do not have implementation. In order to create an abstract method, you use the
abstract
keyword as follows:
An abstract class is a class that contains at least one abstract method. To declare an abstract class, you also use the
abstract
keyword as follows:PHP abstract class example
Let’s take a look at an example to understand how abstract class and abstract method work. We will develop new classes based on the following class diagram:
PHP Abstract Class Example
firstname
and $lastname.
An abstract class can contain methods that are fully implemented e.g.
__toString()
method.
The abstract class allows you to declare a class that has a partial implementation. The subclasses will provide specific implementation for abstract methods.
The classes that inherit an abstract class are called concrete classes, e.g.,
Employee
class and Contractor
class are concrete classes.
The following illustrates how to use the
Employee
class:
We can develop another concrete class named
Contractor
as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<?php
require_once 'classes/person.php';
class Contractor extends Person{
private $rate;
private $billableHours;
public function __construct($firstName, $lastName,$rate, $billableHours){
parent::__construct($firstName, $lastName);
$this->rate = $rate;
$this->billableHours = $billableHours;
}
public function getSalary(){
return $this->rate * $this->billableHours;
}
public function __toString(){
return sprintf("Name:%s<br>Salary:$%0.2f",
parent::__toString(),
$this->getSalary());
}
}
|
And the sample code that uses the
Contractor
class:
No comments:
Post a Comment