Computer >> 컴퓨터 >  >> 프로그래밍 >> PHP

PHP 인터페이스 완벽 가이드: 기본 문법부터 다중 상속 활용까지

인터페이스란 무엇인가?

인터페이스(Interface)는 객체 지향 프로그래밍(OOP)의 핵심 기능 중 하나로, 클래스가 반드시 구현해야 할 메서드를 정의하되 그 구현 방법까지는 강제하지 않는 강력한 도구입니다. 즉, "무엇을 해야 하는가"만 규정하고 "어떻게 할 것인가"는 구현하는 클래스에 맡기는 방식입니다.

PHP에서는 interface 키워드를 사용해 인터페이스를 선언합니다. 인터페이스는 클래스와 비슷하게 생겼지만, 메서드의 본문(body)이 없다는 점이 다릅니다. 또한 인터페이스 내의 모든 메서드는 반드시 public으로 선언되어야 합니다.

인터페이스를 상속받아 구현하는 클래스는 extends 대신 implements 키워드를 사용해야 하며, 부모 인터페이스에 선언된 모든 메서드를 빠짐없이 구현해야 합니다.

기본 문법

<?php
interface testinterface {
    public function testmethod();
}

class testclass implements testinterface {
    public function testmethod() {
        echo "implements interface method";
    }
}
?>

구현 클래스는 인터페이스에 선언된 모든 메서드를 반드시 정의해야 합니다. 하나라도 누락되면 PHP 파서가 치명적인 오류(fatal error)를 발생시킵니다.

메서드 미구현 시 발생하는 오류

다음 예제에서는 인터페이스에 선언된 두 개의 메서드 중 하나만 구현했습니다.

<?php
interface testinterface {
    public function test1();
    public function test2();
}

class testclass implements testinterface {
    public function test1() {
        echo "implements interface method";
    }
}
$obj = new testclass();
?>

이 코드를 실행하면 아래와 같은 오류가 출력됩니다.

PHP Fatal error: Class testclass contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (testinterface::test2)

오류 메시지는 해당 클래스를 추상(abstract) 클래스로 선언하거나, 남은 메서드(test2)를 구현하라고 안내합니다.

인터페이스의 상속 (extends)

일반 클래스처럼 인터페이스 역시 extends 키워드를 사용해 다른 인터페이스로부터 상속받을 수 있습니다. 자식 인터페이스는 부모 인터페이스의 모든 메서드를 물려받게 됩니다.

다음 예제에서는 testinterface를 상속한 myinterface를 만들고, 이를 구현하는 클래스에서 두 메서드를 모두 정의했습니다.

<?php
interface testinterface {
    public function test1();
}

interface myinterface extends testinterface {
    public function test2();
}

class testclass implements myinterface {
    public function test1() {
        echo "implements test1 method";
    }
    public function test2() {
        echo "implements test2 method";
    }
}
?>

주의할 점은, 자식 인터페이스를 구현하는 클래스는 부모 인터페이스의 메서드까지 포함해 모든 메서드를 구현해야 한다는 것입니다.

인터페이스를 활용한 다중 상속

PHP는 extends 절에서 둘 이상의 클래스를 상속하는 다중 상속을 허용하지 않습니다. 하지만 자식 클래스가 하나 이상의 인터페이스를 구현(implements)하도록 하면 사실상 다중 상속과 같은 효과를 얻을 수 있습니다.

다음 예제에서 myclasstestclass를 확장(extends)함과 동시에 testinterface를 구현하여 두 기능을 모두 갖추게 됩니다.

<?php
interface testinterface {
    public function test1();
}

class testclass {
    public function test2() {
        echo "this is test2 function in parent class\n";
    }
}

class myclass extends testclass implements testinterface {
    public function test1() {
        echo "implements test1 method\n";
    }
}

$obj = new myclass();
$obj->test1();
$obj->test2();
?>

실행 결과

implements test1 method
this is test2 function in parent class

실전 예제: 도형 면적 계산

인터페이스의 실용성을 보여주는 대표적인 예로, 서로 다른 도형 클래스가 동일한 인터페이스를 구현하는 경우를 들 수 있습니다. 아래 예제에서 circle(원)과 rectangle(사각형) 클래스는 각각 shape 인터페이스의 area() 메서드를 자신만의 방식으로 구현합니다.

<?php
interface shape {
    public function area();
}

class circle implements shape {
    private $rad;
    public function __construct() {
        $this->rad = 5;
    }
    public function area() {
        echo "area of circle=" . M_PI * pow($this->rad, 2) . "\n";
    }
}

class rectangle implements shape {
    private $width;
    private $height;
    public function __construct() {
        $this->width = 20;
        $this->height = 10;
    }
    public function area() {
        echo "area of rectangle=" . $this->width * $this->height . "\n";
    }
}

$c = new circle();
$c->area();
$r = new rectangle();
$r->area();
?>

실행 결과

area of circle=78.539816339745
area of rectangle=200

마무리

인터페이스는 코드의 일관성을 보장하고 클래스 간 결합도를 낮춰 유지보수성을 크게 향상시킵니다. 특히 여러 클래스가 동일한 계약(contract)을 따르도록 강제해야 하는 대규모 프로젝트에서 인터페이스는 필수적인 설계 도구입니다. PHP 5부터 도입된 이 기능을 적극 활용하면 더 견고하고 확장 가능한 애플리케이션을 만들 수 있습니다.