php interface 사용방법
Server Side/PHP2016. 10. 1. 20:25
Example #1 인터페이스 예제
// 인터페이스 선언 '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 확장가능한 인터페이스
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 인터페이스 다중 상속
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 인터페이스 상수
interface a
{
const b = 'Interface constant';
}
// Prints: Interface constant
echo a::b;
// 원하는데로 동작하지 않습니다.
// 왜냐하면 재정의를 허용하지 않기 때문입니다.
class b implements a
{
const b = 'Class constant';
}
'Server Side > PHP' 카테고리의 다른 글
| PHP json 인코딩 처리 (0) | 2016.12.02 |
|---|---|
| 서버로 Request 요청 후 DB 인풋 (0) | 2016.11.20 |
| PHP simplexml_load_file 로 XML 파싱 하기 (0) | 2016.09.08 |
| 브라우저 캐시 남기지 않기 (0) | 2016.08.31 |
| 코드이그나이터 설정 (0) | 2016.08.17 |