interface是面向對象編程語言中接口操作的關鍵字,功能是把所需成員組合起來,以封裝一定功能的集合,本文我們來講講interface基本知識及用法實例.
接口是一種約束形式,其中只包括成員定義,不包含成員實現的內容,用接口(interface),你可以指定某個類必須實現哪些方法,但不需要定義這些方法的具體內容,我們可以通過interface來定義一個接口,就像定義一個標準的類一樣,但其中定義所有的方法都是空的.
接口中定義的所有方法都必須是public,這是接口的特性.
實現:要實現一個接口,可以使用implements操作符,類中必須實現接口中定義的所有方法,否則會報一個fatal錯誤,如果要實現多個接口,可以用逗號來分隔多個接口的名稱.
Note:實現多個接口時,接口中的方法不能有重名.
Note:接口也可以繼承,通過使用extends操作符.
常量:接口中也可以定義常量,接口常量和類常量的使用完全相同,它們都是定值,不能被子類或子接口修改.
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
- { //開源軟件:Vevb.com
- private $vars = array();
- public function setVariable($name, $var)
- {
- $this->vars[$name] = $var;
- }
- }
- ?>
Example #2 Extendable Interfaces
- <?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';
- }
- // 輸出接口常量
- echo a::b;
- // 錯誤寫法,因為常量的值不能被修改。接口常量的概念和類常量是一樣的。
- class b implements a
- {
- const b = 'Class constant';
- }
- ?>
新聞熱點
疑難解答