PHP 객체 지향 프로그래밍에서 인터페이스 활용 실습

인터페이스의 실제 적용을 시도해 봅시다. 이전 강의의 도형 문제를 풀어보겠지만, 이번에는 추상 클래스 대신 인터페이스를 사용하겠습니다.

자, 이제 우리에게는 Figure 인터페이스가 주어졌습니다:

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

이 인터페이스의 메서드를 구현하는 Quadrate 클래스를 작성해 봅시다:

Quadrate.php<?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;
    }
  }
?>

작동 원리: 인터페이스에 설명된 메서드 중 하나를 구현하는 것을 잊으면, PHP는 치명적 오류를 표시합니다. 이제 Rectangle 클래스도 구현해 보겠습니다:

Rectangle.php<?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);
    }
  }
?>
Задание 1

인터페이스 Figure를 구현하는 Disk 클래스를 만드세요.