這篇文章主要介紹php中interface有什么用,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
php
中的類是不允許多繼承
的,而接口
可以多繼承
,其次使用接口可以封裝
具體的實(shí)現(xiàn),不向外部暴露具體的實(shí)現(xiàn)細(xì)節(jié),只將接口
暴露出來(lái),用戶也只能夠通過(guò)接口
訪問(wèn),這樣也有一定的安全性。
1.定義:接口,使用interface
關(guān)鍵字定義,與類類似,專門用來(lái)規(guī)范一些共性類必須實(shí)現(xiàn)的方法。
interface People{}
2.接口實(shí)現(xiàn):接口是用來(lái)規(guī)范類必須完成的事情,所以接口只能被類實(shí)現(xiàn):implements
。(不允許實(shí)例化)
class Man implements People{}
3 .接口成員:接口中只能定義公有抽象方法
和接口常量
interface Animal{ const NAME = '人';//只允許有接口常量 public function eat();//接口方法必須為公有抽象方法 }
4.接口的實(shí)現(xiàn)類必須實(shí)現(xiàn)所有的抽象方法
,或者實(shí)現(xiàn)類為抽象類
,接口常量
可以直接在實(shí)現(xiàn)類中訪問(wèn)
interface Animal{ const NAME = '人'; public function eat(); } //實(shí)現(xiàn)接口 class Man implements Human{ //必須實(shí)現(xiàn)接口所有抽象方法 public function eat(){ echo self::NAME; //可以訪問(wèn)接口常量 } } //抽象類實(shí)現(xiàn)接口 abstract class Ladyboy implements Human{} //正常實(shí)現(xiàn)
5.實(shí)現(xiàn)接口的類成員
,不允許重寫接口中的常量,不允許增加接口方法的控制權(quán)限
interface Animal{ const NAME = '人'; public function eat(); } class Woman implements Human{ //重寫接口常量 const NAME = '女人'; //錯(cuò)誤:不允許重寫接口常量 //強(qiáng)化接口方法控制 private function eat(){} //錯(cuò)誤:接口方法不允許使用其他訪問(wèn)修飾限定符,必須使用public }
6.接口可以繼承接口:extends
,而且接口可以多繼承接口
interface Plant{ public function lightning(); } interface Animal{ public function eat(); } //單繼承 interface Man extends Animal{} //多繼承 interface Apple extends Plant,Animal{}
以上是“php中interface有什么用”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!