Abstract Methods in OOP in PHP
Abstract classes can also contain abstract methods. Such methods should not have an implementation; they are needed to indicate that such methods must be present in the descendants. And the actual implementation of these methods is the task of the descendants.
To declare a method as abstract,
the keyword abstract
should be written
during its declaration.
Let's try it in practice. Suppose it is assumed
that all descendants of the User
class must
have the method increaseRevenue
.
This method should take the user's current income and increase it by a certain amount, passed as a parameter.
The User
class itself does not know what kind of
income the descendant will have - for an employee
it's a salary, while for a student it's a scholarship. Therefore,
each descendant will implement this method
in its own way.
The point here is that the abstract method of the
User
class forces the programmer to implement
this method in the descendants; otherwise, PHP will throw an error.
Thus, you, or another programmer
working with your code, will not be able
to forget to implement the required method
in a descendant.
So, let's try it in practice. Let's add
an abstract method increaseRevenue
to the User
class:
<?php
abstract class User
{
private $name;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
// Abstract method without a body:
abstract public function increaseRevenue($value);
}
?>
Let our Employee
class remain
unchanged for now. In this case, even if we don't
create an object of the Employee
class,
but simply run the code where our classes are defined,
- PHP will throw an error.
Let's now write the implementation of the
increaseRevenue
method in the
Employee
class:
<?php
class Employee extends User
{
private $salary;
public function getSalary()
{
return $this->salary;
}
public function setSalary($salary)
{
$this->salary = $salary;
}
// Let's write the method implementation:
public function increaseRevenue($value)
{
$this->salary = $this->salary + $value;
}
}
?>
Let's test our class:
<?php
$employee = new Employee;
$employee->setName('john');
$employee->setSalary(1000);
$employee->increaseRevenue(100);
echo $employee->getSalary();
?>
Let's implement the increaseRevenue
method
in the Student
class as well. Only now our
method will increase the scholarship:
<?php
class Student extends User
{
private $scholarship; // scholarship
public function getScholarship()
{
return $this->scholarship;
}
public function setScholarship($scholarship)
{
$this->scholarship = $scholarship;
}
// The method increases the scholarship:
public function increaseRevenue($value)
{
$this->scholarship = $this->scholarship + $value;
}
}
?>
Add the same
abstract method increaseRevenue
to your User
class.
Write the implementation of this method in the
Employee
and Student
classes.
In the Figure
class, make abstract
methods for getting the area and perimeter of the figure.