在學習框架閱讀框架源碼的時候,會看到底層很多interface類,類中定義了一些方法,但僅僅就是定義了方法而已,稱作接口對象。對于php的interface類,實現接口用implements,并且必須完全實現接口類中的方法,例如:
//定義接口
interface User{
function getDiscount();
function getUserType();
}
//VIP用戶 接口實現
class VipUser implements User{
// VIP 用戶折扣系數
private $discount = 0.8;
function getDiscount() {
return $this->discount;
}
function getUserType() {
return "VIP用戶";
}
}
class Goods{
var $price = 100;
var $vc;
//定義 User 接口類型參數,這時并不知道是什么用戶
function run(User $vc){
$this->vc = $vc;
$discount = $this->vc->getDiscount();
$usertype = $this->vc->getUserType();
echo $usertype."商品價格:".$this->price*$discount;
}
}
$display = new Goods();
$display ->run(new VipUser); //可以是更多其他用戶類型
?>
運行該例子:VIP用戶商品價格:80元。
user接口類,之提供了用戶折扣方法,VipUser類實現了具體折扣系數,goods類實現了不同用戶的折扣系數。
所以對于一個團隊開發的項目,比如我 負責Vip用戶的折扣,你負責其他用戶的折扣,我們只要定義好一個interface,在我們邏輯 中去實現這個類就可。
php也能在繼承一個類的時候實現多接口:
class A extends B implements C,D{}