Inheritance from a Class and Implementation of an Interface in OOP in PHP
A class can inherit from another class and at the same time implement some interface. Let's consider a practical example.
Suppose we want to create a class Programmer
,
which will have a name, salary, and a list of languages
that the programmer knows.
Our class description is rather vague so far:
yes, the class will have a name, salary, languages -
but what methods will our class have?
Let's describe our class more accurately using
the interface iProgrammer
:
<?php
interface iProgrammer
{
public function __construct($name, $salary);
public function getName();
public function getSalary();
public function getLangs();
public function addLang($lang);
}
?>
Suppose we dug into our already implemented
classes and, it turns out, we already have a similar
class Employee
. It does not implement all
the methods of the Programmer
class, but some.
Here is the code of our existing class:
<?php
class Employee
{
private $name;
private $salary;
public function __construct($name, $salary)
{
$this->name = $name;
$this->salary = $salary;
}
public function getName()
{
return $this->name;
}
public function getSalary()
{
return $this->salary;
}
}
?>
It is logical in our case to make it so that
our new class Programmer
inherits
some of the methods it needs from the class
Employee
(and we will implement the rest
later in the new class itself):
<?php
class Programmer extends Employee
{
}
?>
At the same time, we know that the Pogrammer
class
should implement the interface
iProgrammer
:
<?php
class Programmer implements iProgrammer
{
}
?>
Let's combine inheritance from the class
Employee
and implementation of the interface
iProgrammer
:
<?php
class Programmer extends Employee implements iProgrammer
{
}
?>
It turns out that our Pogrammer
class
will inherit from the Employee
class the methods
__construct
, getName
and getSalary
,
and the methods addLang
and getLangs
we will have to implement ourselves:
<?php
class Programmer extends Employee implements iProgrammer
{
public function addLang($lang)
{
// implementation
}
public function getLangs()
{
// implementation
}
}
?>
The iProgrammer
interface doesn't care
whether the methods are native to the class or inherited -
the main thing is that all the described methods are
implemented.
Copy the code of my Employee
class
and the code of the iProgrammer
interface. Do not copy
my template of the Programmer
class -
without looking at my code, implement this
class yourself.