PHP物件導向:介面與抽象方法

來源:互聯網
上載者:User

介面(interface)是抽象方法和靜態常量定義的集合。

介面是一種特殊的抽象類別,這種抽象類別中只包含抽象方法和靜態常量。

介面中沒有其它類型的內容。

我們先寫介面的定義,下面的例子是介面的一個簡單寫法。

view sourceprint?1 interface 介面名{ 

2 }

下面的例子定義了一個介面 user ,這個介面中有兩個抽象方法,getname() 和 setname()。能看到介面的寫法和類很相似。

view sourceprint?1 <? 

2 interface user { 

3     function getname(); 

4     function setname($_name);    

5 } 

6 ?>

注意,在介面中只能有抽象方法。如果在介面中出現了非抽象方法,會報錯如下:

interface function user::setname() cannot contain body in ……….

view sourceprint?1 <? 

2 interface user { 

3     function getname(); 

4     function setname($_name){}   

5 } 

6 ?>

程式運行如下:

view sourceprint?1 fatal error: interface function user::setname() cannot contain body in e:phpprojects est.php on line 4

在介面中的抽象方法只能是public的,預設也是public許可權。

並且不能設定成 private 或者 protected 類型。

否則會報錯如下:

access type for interface method user::setname() must be omitted in —on line —

在介面中,訪問類型必須忽略。

view sourceprint?1 <? 

2 interface user { 

3     public function getname(); 

4     private function setname($_name);    

5 } 

6 ?>

程式運行如下:

view sourceprint?1 fatal error: access type for interface method user::setname() must be omitted in e:phpprojects est.php on line 4

protected存取權限也會有問題

view sourceprint?1 <? 

2 interface user { 

3     public function getname(); 

4     protected function setname($_name);  

5 } 

6 ?>

程式運行如下:

view sourceprint?1 fatal error: access type for interface method user::setname() must be omitted in e:phpprojects est.php on line 4

即使abstract 和 final 修飾符不能修飾介面中的抽象方法。

view sourceprint?1 <? 

2 interface user { 

3     final function getname(); 

4     abstract  function setname($_name);  

5 } 

6 ?>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.