객체 인터페이스는 클래스가 반드시 구현해야할 메서드를 해당 메서드가 어떻게 동작하는지 알 필요없이 지정하는 코드를 만들수 있습니다.
인터페이스는 interface 키워드를 사용해 정의할 수 있습니다. 일반클래스와 방식이 같지만, 메서드의 구현부가 정의되지 않음이 다릅니다.
interface 내부의 모든 메서드는 반드시 public 이어야만 합니다; 이것은 interface 의 특성입니다.
인터페이스를 구현하기 위해서는, implements 키워드가 사용됩니다. 인터페이스 내부의 모든 메서드는 클래스 안에 모두 구현되어야 합니다.; 그렇지 않을경우 fata error에 마주하게 됩니다. 각각의 인터페이스를 쉼표로 구분하여 지정하면 클래스는 하나 이상의 인터페이스를 구현할수 있습니다.
Note:
PHP 5.3.9 이전에서는, 두개의 인터페이스가 같은 메서드명을 정의하고 있을 경우 클래스를 구현할수 없었습니다. 모호하기 때문입니다. 최근의 버전에서는 메서드명이 같더라도 메서드의 시그너쳐(메서드 정의 형태)가 완전히 동일할 경우에는 구현이 가능합니다.
Note:
인터페이스도 클래스처럼 extends 키워드를 사용해 확장이 가능합니다.
Note:
인터페이스를 구현하는 클래스는 인터페이스에 정의된 메서드와 완전히 동일한 메서드 시그너쳐를 사용해야 합니다. 그렇지 않을 경우 fatal error 에 마주할 것입니다.
인터페이스가 상수를 가지는것이 가능합니다. 인터페이스 상수는 클래스 상수와 완전히 동일하게 동작합니다. 하지만, 상속받은 클래스/인터페이스 에서 재정의 할수 없습니다.
Example #1 인터페이스 예제
<?php
// 인터페이스 선언 'iTemplate'
interface iTemplate
{
public function setVariable($name, $var);
public function getHtml($template);
}
// 인터페이스 구현
// 동작합니다.
class Template implements iTemplate
{
private $vars = array();
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
public function getHtml($template)
{
foreach($this->vars as $name => $value) {
$template = str_replace('{' . $name . '}', $value, $template);
}
return $template;
}
}
// 동작하지 않습니다.
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
private $vars = array();
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
}
?>
Example #2 확장가능한 인터페이스
<?php
interface a
{
public function foo();
}
interface b extends a
{
public function baz(Baz $baz);
}
// 동작합니다.
class c implements b
{
public function foo()
{
}
public function baz(Baz $baz)
{
}
}
// 동작하지 않고 fatal error 가 납니다.
class d implements b
{
public function foo()
{
}
public function baz(Foo $foo)
{
}
}
?>
Example #3 인터페이스 다중 상속
<?php
interface a
{
public function foo();
}
interface b
{
public function bar();
}
interface c extends a, b
{
public function baz();
}
class d implements c
{
public function foo()
{
}
public function bar()
{
}
public function baz()
{
}
}
?>
Example #4 인터페이스 상수
<?php
interface a
{
const b = 'Interface constant';
}
// Prints: Interface constant
echo a::b;
// 원하는데로 동작하지 않습니다.
// 왜냐하면 재정의를 허용하지 않기 때문입니다.
class b implements a
{
const b = 'Class constant';
}
?>
인터페이스에서, 타입힌팅을 사용하면, 특정 객체에 특정 메서드를 가지게 하는 좋은 방법을 제공합니다. instanceof 와 타입 힌트를 보시기 바랍니다.