我们在通过学习VideoCard.php 接口文件(显卡的功能接口定义)
<ol class="dp-xml"><li class="alt"> <span><strong><font color="#006699"><span class="tag"><?</SPAN><SPAN class=tag-name>php</SPAN></FONT></STRONG><SPAN> </SPAN></SPAN><LI class=""><SPAN>interface VideoCardInter{ </SPAN><LI class=alt><SPAN> function Display(); </SPAN><LI class=""><SPAN> function getName(); </SPAN><LI class=alt><SPAN>} </SPAN><LI class=""><SPAN></SPAN><SPAN class=tag><STRONG><FONT color=#006699>?></span></font></strong></span><span> </span> </li></ol>
Dmeng.php 实现接口(帝盟的厂家实现了这些接口,怎么实现的,主板厂家不用管)
<ol class="dp-xml"><li class="alt"> <span><strong><font color="#006699"><span class="tag"><?</SPAN><SPAN class=tag-name>php</SPAN></FONT></STRONG><SPAN> </SPAN></SPAN><LI class=""><SPAN>include_once("VideoCard.php"); </SPAN><LI class=alt><SPAN>class Dmeng implements VideoCardInter { </SPAN><LI class=""><SPAN> function Display(){ </SPAN><LI class=alt><SPAN> echo "Display"; </SPAN><LI class=""><SPAN> } </SPAN><LI class=alt><SPAN> function getName(){ </SPAN><LI class=""><SPAN> return "Dmeng VideoCard"; </SPAN><LI class=alt><SPAN> } </SPAN><LI class=""><SPAN>} </SPAN><LI class=alt><SPAN></SPAN><SPAN class=tag><STRONG><FONT color=#006699>?></span></font></strong></span><span> </span> </li></ol>
Mainboard.php 应用接口(把显卡插到主板上,主板只要用这些接口就行了,也可以不用)
<ol class="dp-xml"> <li class="alt"> <span><strong><font color="#006699"><span class="tag"><?</SPAN><SPAN class=tag-name>php</SPAN></FONT></STRONG><SPAN> </SPAN></SPAN><LI class=""><SPAN>include_once("VideoCard.php"); </SPAN><LI class=alt><SPAN>include_once("Dmeng.php"); </SPAN><LI class=""><SPAN>class Mainboard{ </SPAN><LI class=alt><SPAN> var $vc; </SPAN><LI class=""><SPAN> function run(VideoCardInter $vc){ //定义VideoCardInter接口类型参数,这时并不知道是谁来实现。 </SPAN><LI class=alt><SPAN> $this-</SPAN><SPAN class=tag><STRONG><FONT color=#006699>></span></font></strong></span><span class="attribute"><font color="#ff0000">vc</font></span><span>=$vc; </span> </li> <li class=""> <span> $this-</span><span class="tag"><strong><font color="#006699">></font></strong></span><span>vc-</span><span class="tag"><strong><font color="#006699">></font></strong></span><span>Display(); </span> </li> <li class="alt"><span> echo "主板运行!"; </span></li> <li class=""><span> } </span></li> <li class="alt"><span>} </span></li> <li class=""> <span>$</span><span class="attribute"><font color="#ff0000">conputer</font></span><span>=</span><span class="attribute-value"><font color="#0000ff">new</font></span><span> Mainboard(); </span> </li> <li class="alt"> <span>$conputer-</span><span class="tag"><strong><font color="#006699">></font></strong></span><span>run(new Dmeng); //用的时候把实现接口类的名称写进来,<br>(现在是帝盟的显卡,也可以换成别的场家的,只要他们都实现了接口) </span> </li> <li class=""> <span></span><span class="tag"><strong><font color="#006699">?></font></strong></span><span> </span> </li> </ol>
由于PHP是动态语言,所以类型不能像JAVA一样定的很死,定义接口的时候,写上返回类型反而出错,估计PHP6的时候可能写义的要严格一些吧。
PS:我只把PHP接口特性最基本的部分写上,还可以加CPU等接口。