Constants in Interface in OOP in PHP
Interfaces cannot contain class properties, but they can contain constants. Interface constants work exactly the same as class constants, with the exception that they cannot be overridden by an inheriting class or interface.
For example, let's create an interface iSphere
,
which will describe a class for working
with a sphere. For this sphere, we will need to find
the volume and surface area. For this, we
will need the number Pi. Let's define it as a constant
of our interface:
<?php
interface iSphere
{
const PI = 3.14; // the number PI as a constant
// Sphere constructor:
public function __construct($radius);
// Method for finding the volume of a sphere:
public function getVolume();
// Method for finding the surface area of a sphere:
public function getSquare();
}
?>
Create a class Sphere
that will
implement the interface iSphere
.