Prax na aplikáciu rozhraní v OOP v PHP
Vyskúšajme si aplikáciu rozhraní v praxi. Vyriešme úlohu s obrazcami z predchádzajúcej lekcie, ale tentoraz pomocou rozhraní, nie abstraktných tried.
Takže teraz máme dané rozhranie Figure:
<?php
interface Figure
{
public function getSquare();
public function getPerimeter();
}
?>
Napíšme triedu Quadrate, ktorá
bude implementovať metódy tohto rozhrania:
<?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;
}
}
?>
Ako to funguje: ak zabudneme implementovať
nejakú metódu opísanú v rozhraní,
PHP nám vypíše fatálnu chybu. Implementujme
aj triedu Rectangle:
<?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);
}
}
?>
Vytvorte triedu Disk,
implementujúcu rozhranie Figure.