Multiple Interfaces in OOP in PHP
PHP does not have multiple inheritance - each
class can have only one parent.
However, with interfaces, things are different:
each class can implement any number of
interfaces. To do this, the interface names
need to be listed after the keyword
implements, separated by commas.
This demonstrates another difference between interfaces and abstract classes - you can implement many interfaces, but you cannot inherit from several abstract classes.
Let's try it in practice. Suppose that besides
the interface iFigure we also have
an interface iTetragon.
The methods of this interface will be implemented by
the classes Quadrate and Rectangle,
since they have 4 sides, but not the class
Disk.
Let the interface iTetragon describe
getters for all four sides
of a quadrilateral:
<?php
interface iTetragon
{
public function getA();
public function getB();
public function getC();
public function getD();
}
?>
Suppose we also have the interface iFigure,
which we created earlier:
<?php
interface iFigure
{
public function getSquare();
public function getPerimeter();
}
?>
Let's make the class Quadrate
implement two interfaces. To do this, we list
both interfaces after the keyword
implements, separated by a comma:
<?php
class Quadrate implements iFigure, iTetragon
{
// implementation will be here
}
?>
Now let's finalize our class Quadrate,
so that it implements the interface iTetragon.
It is clear that our square is a degenerate
case of a quadrilateral, because a square has
all sides equal. Therefore, all new methods
will return the same thing - the width of the square:
<?php
class Quadrate implements iFigure, iTetragon
{
private $a;
public function __construct($a)
{
$this->a = $a;
}
public function getA()
{
return $this->a;
}
public function getB()
{
return $this->a;
}
public function getC()
{
return $this->a;
}
public function getD()
{
return $this->a;
}
public function getSquare()
{
return $this->a * $this->a;
}
public function getPerimeter()
{
return 4 * $this->a;
}
}
?>
Obviously, in a rectangle, not all
sides are the same, only the opposite ones are.
In this case, the new methods will be slightly
different. Well, and in some trapezoid,
all 4 sides will be completely different.
However, it doesn't matter what kind of figure we are considering - what is important is that all these figures will have the described methods (even if some figures are degenerate) and work in a uniform way.
Make the class Rectangle
also implement two interfaces: both iFigure,
and iTetragon.
Create an interface iCircle with methods
getRadius and getDiameter.
Make the class Disk also
implement two interfaces: both iFigure,
and iCircle.