PHP 오브젝트 인터페이스

PHP/매뉴얼 번역 2008/06/20 00:07
오브젝트 인터페이스(Object Interfaces)

오브젝트인터페이스를 이용해서 메소드의 실체를 정의 하지 않고도 어떤 클래스가 구현해야하는 메소드의 종류를 지정하는 코드를 생성할수 있다.
인터페이스는 키워드 interface 로 정의되며 일반적인 클래스처럼 정의 할수 있지만 메소드의 구현은 정의되지 않는다.
인터페이스내에서 선언되는 모든 메소드는 public 이어야 한다.  

implements

인터페이스를 구현하기위해서는 implements  연산자를 사용하며 , 이 인터페이스에 포함되는 모든 메소드를 구현해야한다.  구현되지 않은 경우 치명적인 에러를 발생한다. 각각의 인터페이스를 콤마로 구분해서 지정하여 클래스는 복수의 인터페이스를 구현할 수 있다.

주의 : 하나의 클래스내에서 같은이름의 함수를 가지고 있는 2개의 인터페이스를 구현할 수 없다.


<?php
// Declare the interface 'iTemplate'
interface iTemplate
{
    public function
setVariable($name, $var);
    public function
getHtml($template);
}

// Implement the interface
// This will work
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;
    }
}

// This will not work
// 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;
    }
}

?>

원문링크: http://www.php.net/manual/en/language.oop5.interfaces.php

목차로
PHP 클래스와 오브젝트 ( Classes and Objects ) PHP 5

'PHP > 매뉴얼 번역' 카테고리의 다른 글

PHP final 키워드  (0) 2008/06/20
PHP 매직메소스  (0) 2008/06/20
PHP 패턴  (0) 2008/06/20
PHP 오브젝트 이터레이션  (0) 2008/06/20
PHP 오버로드  (0) 2008/06/20
PHP 오브젝트 인터페이스  (0) 2008/06/20
PHP 클래스의 추상화  (0) 2008/06/19
PHP 클래스 정수  (0) 2008/06/19
PHP static 키워드  (0) 2008/06/19
PHP 스코프 연산자(::)  (0) 2008/06/19
PHP 억세스권(접근권한) : Visibility  (0) 2008/06/19
Trackback 0 : Comment 0