RussellHouse
[PHP] 25. Interface (인터페이스) 본문
인터페이스는 서로 다른 시스템이 결합되는 접점을 의미한다.
이 때 서로 시스템이 잘 결합하기 위해서는 상호간에 엄격한 약속이 필요하다.
프로그래밍에서의 인터페이스도 마찬가지이다.
이 수업에서는 프로그래밍에서는 어떻게 인터페이스를 구현하는가를 알아보도록 하자.
우리는 특정 클래스가 특정한 이름의 함수를 구현하도록 하고 싶을 수 있는데,
이러한 경우에 사용할 수 있는 유용한 도구가 interface 이다.
자세한 내용은 아래의 예제를 살펴보도록 하자.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <?php interface ContractInterface { public function promiseMethod( array $param ):int; } interface ContractInterface2 { public function promiseMethod2( array $param ):int; } class ConcreateClass implements ContractInterface, ContractInterface2 { public function promiseMethod( array $param ):int { return 1; } public function promiseMethod2( array $param ):int { return 1; } } $obj = new ConcreateClass(); $obj ->promiseMethod([1,2]); |
위의 2번, 6번 라인과 같이, interface를 통하여 특정 메소드와 이에 대한 인자, 구성등을 설정할 수 있다.
다음으로, 11번 라인과 같이 클래스를 정의하고 implements를 통해 어떠한 클래스에 어떠한 interface를 강
제해야하는가를 설정 할 수 있다.
강제된 클래스 내부에는 interface에서 설정한 내용을 준수한 컨텐츠들이 구현되어야 한다.
만일 implements를 통하여 강제 당한 사항들이 해당 클래스내에 존재하지 않는 경우, Error가 발생한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <?php interface ContractInterface { public function compare(string $str1 , string $str2 ):bool; } class Concreate implements ContractInterface { public function compare(string $str1 , string $str2 ):bool { if ( $str1 === $str2 ) return true; else return false; } } class Dummy implements ContractInterface { public function compare(string $str1 , string $str2 ):bool { return true; } } $obj = new Concreate(); if ( $obj ->compare( 'test1' , 'test2' )) { echo '<h1>same</h1>' ; } else { echo '<h1>different</h1>' ; } |
또한, Interface는 사회적인 약속이기 때문에, 의미를 명확하게 전달할 수 있으며,
정보를 교류하는데에도 유용하다.
'PHP' 카테고리의 다른 글
[PHP] 26. Abstract (0) | 2017.12.04 |
---|---|
[PHP] 23. File Uploading (파일 업로드) (0) | 2017.11.28 |
[PHP] 22. Directory control (디렉토리 제어) (0) | 2017.11.28 |
[PHP] 21. File Control (파일 제어) (0) | 2017.11.28 |
[PHP] 20. Database (데이터베이스) (0) | 2017.11.28 |
Comments