Abstract Classes in OOP in PHP
Suppose you have a class User, and
classes Employee and Student
inherit from it.
It is assumed that you will create
objects of the classes Employee and Student,
but you will not create objects of the class User,
as this class is used only for
grouping common properties and methods of its
descendants.
In this case, you can forcibly prohibit
creating objects of the class User, so that
you or another programmer do not accidentally
create them somewhere.
For this, there are so-called abstract classes. Abstract classes are classes intended for inheritance from them. At the same time, objects of such classes cannot be created.
To declare a class abstract,
you need to write the keyword
abstract during its declaration:
<?php
abstract class User
{
}
?>
So, let's write the implementation of the abstract
class User. Let it have a private
property name, as well as getters and setters
for it:
<?php
abstract class User
{
private $name;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
}
?>
An attempt to create an object of the class User
will cause an error:
<?php
$user = new User; // will throw an error
?>
But it will be possible to inherit from our class.
Let's create a class Employee, which
will inherit from our abstract
class User:
<?php
class Employee extends User
{
private $salary;
public function getSalary()
{
return $this->salary;
}
public function setSalary($salary)
{
$this->salary = $salary;
}
}
?>
Let's create an object of the class Employee -
everything will work:
<?php
$employee = new Employee;
$employee->setName('john'); // parent's method, i.e. from the User class
$employee->setSalary(1000); // its own method, i.e. from the Employee class
echo $employee->getName(); // will output 'john'
echo $employee->getSalary(); // will output 1000
?>
Make an abstract class Figure,
representing a geometric
figure. Let classes for a circle, rectangle, and square
inherit from it.