⊗ppOpIfPrm 66 of 107 menu

Practice on Using Interfaces in OOP in PHP

Let's try using interfaces in practice. Let's solve the problem with shapes from the previous lesson, but now using interfaces, not abstract classes.

So, now we are given the Figure interface:

<?php interface Figure { public function getSquare(); public function getPerimeter(); } ?>

Let's write a Quadrate class that will implement the methods of this interface:

<?php class Quadrate implements Figure { private $a; public function __construct($a) { $this->a = $a; } public function getSquare() { return $this->a * $this->a; } public function getPerimeter() { return 4 * $this->a; } } ?>

How it works: if you forget to implement any method described in the interface, PHP will throw a fatal error. Let's also implement the Rectangle class:

<?php class Rectangle implements Figure { 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); } } ?>

Create a Disk class that implements the Figure interface.

byenru