Constructor Declaration in Interface in OOP in PHP
In an interface, you can also declare a class
constructor. Let's look at an example. Suppose we decided
to make a Rectangle
class, which
will have methods for finding the area, perimeter,
and also a constructor that takes two parameters.
Let's describe our class using an interface:
<?php
interface iRectangle
{
public function __construct($a, $b); // constructor with two parameters
public function getSquare();
public function getPerimeter();
}
?>
Let's write the implementation of our interface
iRectangle
:
<?php
class Rectangle implements iRectangle
{
private $a;
private $b;
public function __construct($a, $b)
{
$this->a = $a;
$this->b = $b;
}
public function getSquare()
{
return $this->a * $this->b;
}
public function getPerimeter()
{
return 2 * ($this->a + $this->b);
}
}
?>
What did declaring a constructor in the interface give us? Firstly, we will not forget to implement the constructor in the class. Secondly, the interface explicitly indicates that the class constructor must accept two parameters: no more, no less. This also protects us from accidental error.
Why did we create a separate interface iRectangle
,
and did not add the constructor to the Figure
interface?
Because all figures have a different number of
sides and, accordingly, a different number of
parameters in the constructor. Therefore, we had to
create a separate, more precise interface
specifically for rectangles.
Make an interface iCube
, which
will describe the Cube figure. Let your interface
describe a constructor that takes the side of the cube as a parameter,
as well as methods for getting
the volume of the cube and the surface area.
Make a Cube
class that implements the interface
iCube
.
Make an interface iUser
, which
will describe a user. It is assumed that
the user will have a name and age and these fields will be
passed by the constructor parameters. Let
your interface also specify that the user
will have getters (but not setters) for the name and
age.
Make a User
class that implements the interface
iUser
.