面向對象編程中,類和接口是最基礎的兩個概念了。下面寫一個簡單的程序,分別演示使用基類與接口如何編寫程序。程序很簡單,不用過多解釋,直接上代碼了。廣大程序員兄弟們一定能夠明白是什麼意思吧。
先是類的方式。
<?php
/**
* 類模式老婆
* Wife基類
*/
class Wife {
public function Cook($howToCook, $vegetableArray) {
$this->BuyVegetables ( $vegetableArray );
for($i = 0; $i < count ( $howToCook ); $i ++) {
//要吃的菜沒有?買去
if (in_array ( $howToCook [$i] ["one"], $vegetableArray )) {
$this->BuyVegetables ( array ($howToCook [$i] ["one"] ) );
} else if (in_array ( $howToCook [$i] ["two"], $vegetableArray )) {
$this->BuyVegetables ( array ($howToCook [$i] ["two"] ) );
} else {
"做飯";
}
}
}
/**
* 買菜
* @param array $vegetableArray 菜名數組
*/
public function BuyVegetables($vegetableArray) {
"去菜場買菜";
}
/**
* 洗衣服
*/
public function WashClothes() {
"1_干洗外套";
"2_洗衣機洗褲子";
"3_手洗襪子";
}
/**
* 做家務
*/
public function DoHouseholdDuties() {
"1_掃地";
"2_拖地";
"3_擦桌子";
}
}
/**
* I類 繼承Wife類
* @author Samuel
*/
class I extends Wife {
/**
*打游戲
*/
function PlayGames() {
"打游戲";
}
/**
* 打籃球
*/
function PlayBasketball() {
"打籃球";
}
/**
* 看電視
*/
function WatchTV() {
"看電視";
}
/**
* 煮飯
* @see Wife::Cook()
*/
function Cook() {
//哥哥今天要吃的菜
$howToCook = array (array ("one" => "豬肉", "two" => "芹菜", "operation" => "炒" ), array ("one" => "土豆", "two" => "牛肉", "operation" => "燒" ) );
$vegetableArray = array ("豬肉", "雞蛋", "酸奶", "香菇", "芹菜", "土豆", "牛肉" );
parent::Cook ( $howToCook, $vegetableArray );
}
/**
* 洗衣服
* @see Wife::WashClothes()
*/
function WashClothes() {
//調用Wife類洗衣服方法
parent::WashClothes ();
}
/**
* 做家務
* @see Wife::DoHouseholdDuties()
*/
function DoHouseholdDuties() {
//調用Wife類做家務方法
parent::DoHouseholdDuties ();
}
}
?>
然後是接口的方式:
<?php
/**
* 接口模式老婆
* Wife接口
*/
interface Wife {
/**
* 煮飯
* @param array $howToCook 菜的做法
* @param array $vegetableArray 需買的菜的數組
*/
function Cook($howToCook, $vegetableArray) {
}
/**
* 買菜
* @param array $vegetableArray 菜名數組
*/
function BuyVegetables($vegetableArray) {
}
/**
* 洗衣服
*/
function WashClothes() {
}
/**
* 做家務
*/
function DoHouseholdDuties() {
}
}
/**
* I類 實現Wife接口
* @author Samuel
*/
class I implements Wife {
/**
*打游戲
*/
function PlayGames() {
"打游戲";
}
/**
* 打籃球
*/
function PlayBasketball() {
"打籃球";
}
/**
* 看電視
*/
function WatchTV() {
"看電視";
}
/**
* 煮飯
* @param array $howToCook 菜的做法
* @param array $vegetableArray 需買的菜的數組
*/
public function Cook($howToCook, $vegetableArray) {
$this->BuyVegetables ( $vegetableArray );
for($i = 0; $i < count ( $howToCook ); $i ++) {
//要吃的菜沒有?買去
if (in_array ( $howToCook [$i] ["one"], $vegetableArray )) {
$this->BuyVegetables ( array ($howToCook [$i] ["one"] ) );
} else if (in_array ( $howToCook [$i] ["two"], $vegetableArray )) {
$this->BuyVegetables ( array ($howToCook [$i] ["two"] ) );
} else {
"做飯";
}
}
}
/**
* 買菜
* @param array $vegetableArray 菜名數組
*/
public function BuyVegetables($vegetableArray) {
"去菜場買菜";
}
/**
* 洗衣服
*/
public function WashClothes() {
"1_干洗外套";
"2_洗衣機洗褲子";
"3_手洗襪子";
}
/**
* 做家務
*/
public function DoHouseholdDuties() {
"1_掃地";
"2_拖地";
"3_擦桌子";
}
}
?>