繼承簡化了對象,類別的創建,增加了程式碼的可重性,但php只支援單繼承,如果要實現多重繼承,就要使用多個介面。
介面透過interface關鍵字來聲明,並且類別中只能包含未實現的方法和一些成員變量,格式如下:
interface interfaceName{
function interfaceName1();
function interfaceName2();
…
}
子類別是透過implements關鍵字來實現接口的,如果要實現多個接口,那麼每個接口之間應使用逗號“,”連接。而且所有未實現的方法都要在子類別中實現,否則php將會出錯。格式如下:
class SubClass implments interfaceName1,interfaceName2{
function interfaceName1(){
//功能實作
}
function interfaceName2(){
//功能實作
}
}
範例程式碼如下:
<code><span><span><span><?php</span><span>//声明接口A</span><span><span>interface</span><span>A</span>{</span><span><span>function</span><span>Aa</span><span>()</span>;</span> } <span>//声明接口B</span><span><span>interface</span><span>B</span>{</span><span><span>function</span><span>Bb</span><span>()</span>;</span> } <span><span>class</span><span>Am</span><span>implements</span><span>A</span>{</span><span><span>function</span><span>Aa</span><span>()</span>{</span><span>echo</span><span>"Aa is a php coder"</span>; } } <span><span>class</span><span>Bm</span><span>implements</span><span>A</span>,<span>B</span>{</span><span><span>function</span><span>Aa</span><span>()</span>{</span><span>echo</span><span>"Mike is a php coder<br>"</span>; <span>echo</span><span>"Mike is an ios coder<br>"</span>; } <span><span>function</span><span>Bb</span><span>()</span>{</span><span>echo</span><span>"Jack is a java coder"</span>; } } <span>$jack</span> =<span>new</span> Am(); <span>$bluce</span> =<span>new</span> Bm(); <span>$jack</span>->Aa(); <span>echo</span><span>"<br>"</span>; <span>$bluce</span>->Aa(); <span>$bluce</span>->Bb(); <span>?></span></span></span></code>
運作結果如下:
以上就介紹了php開發之介面的使用,包括了方面的內容,希望對PHP教學有興趣的朋友有幫助。