在學(xué)習(xí)框架閱讀框架源碼的時(shí)候,會(huì)看到底層很多interface類能曾,類中定義了一些方法熊杨,但僅僅就是定義了方法而已依沮,稱作接口對(duì)象茧球。對(duì)于php的interface類庭瑰,實(shí)現(xiàn)接口用implements,并且必須完全實(shí)現(xiàn)接口類中的方法抢埋,例如:
//定義接口
interface User{
function getDiscount();
function getUserType();
}
//VIP用戶 接口實(shí)現(xiàn)
class VipUser implements User{
// VIP 用戶折扣系數(shù)
private $discount = 0.8;
function getDiscount() {
return $this->discount;
}
function getUserType() {
return "VIP用戶";
}
}
class Goods{
var $price = 100;
var $vc;
//定義 User 接口類型參數(shù)弹灭,這時(shí)并不知道是什么用戶
function run(User $vc){
$this->vc = $vc;
$discount = $this->vc->getDiscount();
$usertype = $this->vc->getUserType();
echo $usertype."商品價(jià)格:".$this->price*$discount;
}
}
$display = new Goods();
$display ->run(new VipUser); //可以是更多其他用戶類型
?>
運(yùn)行該例子:VIP用戶商品價(jià)格:80元。
user接口類揪垄,之提供了用戶折扣方法穷吮,VipUser類實(shí)現(xiàn)了具體折扣系數(shù),goods類實(shí)現(xiàn)了不同用戶的折扣系數(shù)饥努。
所以對(duì)于一個(gè)團(tuán)隊(duì)開發(fā)的項(xiàng)目捡鱼,比如我 負(fù)責(zé)Vip用戶的折扣,你負(fù)責(zé)其他用戶的折扣酷愧,我們只要定義好一個(gè)interface驾诈,在我們邏輯 中去實(shí)現(xiàn)這個(gè)類就可。
php也能在繼承一個(gè)類的時(shí)候?qū)崿F(xiàn)多接口:
class A extends B implements C,D{}