天天看點

[轉]對PHP接口的了解

 ​

以前學JAVA的時候就對接口了解過一回,最近在看PHP的OOP特性,發現和JAVA很像,就是文法上有不同,但是有關資料少的可憐,找到了幾個也不能充分說明PHP下接口的特性,自己又看了一遍孫鑫老師的JAVA視訊教程,有關接口的部分,昨天總算是了解了。真的感覺是豁然開朗。把自己寫的PHP接口部分的示例程式發上來。

VideoCard.php 接口檔案(顯示卡的功能接口定義)

<?php      
interface VideoCardInter{      
function Display();      
function getName();      
}      
?>      

Dmeng.php 實作接口(帝盟的廠家實作了這些接口,怎麼實作的,主機闆廠家不用管)

<?php      
include_once("VideoCard.php");      
class Dmeng implements VideoCardInter {      
function Display(){      
echo "Display";      
}      
function getName(){      
return "Dmeng VideoCard";      
}      
}      
?>      

Mainboard.php  應用接口(把顯示卡插到主機闆上,主機闆隻要用這些接口就行了,也可以不用)

<?php      
include_once("VideoCard.php");      
include_once("Dmeng.php");      
class Mainboard{      
var $vc;      
function run(VideoCardInter $vc){  //定義VideoCardInter接口類型參數,這時并不知道是誰來實作。      
$this->vc=$vc;      
$this->vc->Display();      
echo "主機闆運作!";      
}      
}      
$conputer=new Mainboard(); //執行個體化一台新計算機      
$conputer->run(new Dmeng);  //用的時候把實作接口類的名稱寫進來,(現在是帝盟的顯示卡,也可以換成别的場家的,隻要他們都實作了接口)      
?>      

由于PHP是動态語言,是以類型不能像JAVA一樣定的很死,定義接口的時候,寫上傳回類型反而出錯,估計PHP6的時候可能寫義的要嚴格一些吧。

PS:我隻把最基本的部分寫上,還可以加CPU等接口。

下面是自己寫的三層結構測試代碼

<?php      
$GLOBALS['WebConfig']['DAO'] = "MySql";      
interface IProduct{      
function Display();      
function getName();      
}      
class SqlProductDao implements IProduct {      
function Display(){      
echo "Sql Display";      
}      
function getName(){      
return "Sql Dmeng VideoCard";      
}      
}      
class MySqlProductDao implements IProduct {      
function Display(){      
echo "MySql Display";      
}      
function getName(){      
return "MySql Dmeng VideoCard";      
}      
}      
class DAOFactory{      
public static function getDAO($ClassName){      
$class = new ReflectionClass($GLOBALS['WebConfig']['DAO'].$ClassName);      
$instance = $class->newInstance();      
return $instance;      
}      
}      
class ProductBLL{      
private $iproduct;      
function __construct(IProduct $iproduct){      
$this->iproduct=$iproduct;      
}      
function Display(){      
$this->iproduct->Display();      
}      
function getName(){      
return $this->iproduct->getName();      
}      
}      
$productbill = new ProductBLL(DAOFactory::getDAO("ProductDao"));      
$productbill->Display();      
//echo($productbill->getName());      
?>