객체 인터페이스

객체 인터페이스는 클래스가 반드시 구현해야할 메서드를 해당 메서드가 어떻게 동작하는지 알 필요없이 지정하는 코드를 만들수 있습니다.

인터페이스는 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 
extends a
{
    public function 
baz(Baz $baz);
}

// 동작합니다.
class implements b
{
    public function 
foo()
    {
    }

    public function 
baz(Baz $baz)
    {
    }
}

// 동작하지 않고 fatal error 가 납니다.
class implements b
{
    public function 
foo()
    {
    }

    public function 
baz(Foo $foo)
    {
    }
}
?>

Example #3 인터페이스 다중 상속

<?php
interface a
{
    public function 
foo();
}

interface 
b
{
    public function 
bar();
}

interface 
extends ab
{
    public function 
baz();
}

class 
implements c
{
    public function 
foo()
    {
    }

    public function 
bar()
    {
    }

    public function 
baz()
    {
    }
}
?>

Example #4 인터페이스 상수

<?php
interface a
{
    const 
'Interface constant';
}

// Prints: Interface constant
echo a::b;


// 원하는데로 동작하지 않습니다.
// 왜냐하면 재정의를 허용하지 않기 때문입니다.
class implements a
{
    const 
'Class constant';
}
?>

인터페이스에서, 타입힌팅을 사용하면, 특정 객체에 특정 메서드를 가지게 하는 좋은 방법을 제공합니다. instanceof타입 힌트를 보시기 바랍니다.

add a note add a note

User Contributed Notes 3 notes

up
18
thanhn2001 at gmail dot com
13 years ago
PHP prevents interface a contant to be overridden by a class/interface that DIRECTLY inherits it.  However, further inheritance allows it.  That means that interface constants are not final as mentioned in a previous comment.  Is this a bug or a feature?

<?php

interface a
{
    const
b = 'Interface constant';
}

// Prints: Interface constant
echo a::b;

class
b implements a
{
}

// This works!!!
class c extends b
{
    const
b = 'Class constant';
}

echo
c::b;
?>
up
1
williebegoode at att dot net
9 years ago
In their book on Design Patterns, Erich Gamma and his associates (AKA: "The Gang of Four") use the term "interface" and "abstract class" interchangeably. In working with PHP and design patterns, the interface, while clearly a "contract" of what to include in an implementation is also a helpful guide for both re-use and making changes. As long as the implemented changes follow the interface (whether it is an interface or abstract class with abstract methods), large complex programs can be safely updated without having to re-code an entire program or module.

In PHP coding with object interfaces (as a keyword) and "interfaces" in the more general context of use that includes both object interfaces and abstract classes, the purpose of "loose binding" (loosely bound objects) for ease of change and re-use is a helpful way to think about both uses of the  term "interface." The focus shifts from "contractual" to "loose binding" for the purpose of cooperative development and re-use.
up
-1
xedin dot unknown at gmail dot com
3 years ago
This page says that if extending multiple interfaces with the same methods, the signature must be compatible. But this is not all there is to it: the order of `extends` matters. This is a known issue, and while it is disputable whether or not it is a bug, one should be aware of it, and code interfaces with this in mind.

https://bugs.php.net/bug.php?id=67270
https://bugs.php.net/bug.php?id=76361
https://bugs.php.net/bug.php?id=80785
To Top