PHP4-chap5

物件導向

程式碼

//'5.3'以PHP進行物件導向程式設計-繼承
$session_name = $session_txt['5.3'];
echo $session_name."<br>";

//這個方法比較複雜
$mediaItems = array();
$books = array();
$cds = array();

$item->id			=1;
$item->type			="book";
$item->name			="Professional PHP4";
$item->inStock		=33;
$item->price		=49.95;
$item->rating		=5;
$mediaItems[]	=$item;

$book->isbn			=124465343442;
$book->author		="Ken Egervari";
$book->numberOfPages	=500;
$books[$item->id]	=$book;

$item->id			=2;
$item->type			="cd";
$item->name			="This way";
$item->inStock		=120;
$item->price		=16.94;
$item->rating		=4;
$mediaItems[]	=$item;

$cd->serialNo		=323254354;
$cd->artist			="Jewel";
$cd->numberOfTradks	=13;
$cds[$item->id]	=$cd;

foreach ($mediaItems as $item){
	echo ("Name: " .$item->name. "<br>");
	echo ("Items in stock: " .$item->inStock. "<br>");
	echo ("Price: " .$item->price. "<br>");
	echo ("Rating: " .$item->rating. "<br>");
	
	switch ($item->type){
		case 'cd':
			echo ("Serial No: " .$cds[$item->id]->seriaNo. "<br>");
			echo ("Artist: " .$cds[$item->id]->artist. "<br>");
			echo ("# of Tracks: " .$cds[$item->id]->numberOfTradks. "<br>");
			break;
			
		case 'software':
			break;
		
		case 'movie':
			break;
			
		case 'book':
			break;
	}
}

//用class 繼承 extends
//Media.php
define ("MIN_RATING", 0);
define ("MAX_RATING", 5);


class Media
{
	var $id;
	var $name;
	var $inStock;
	var $price;
	var $rating;
	
	function Media ($id,$name,$inStock,$price,$rating)
	{
		if ($inStock < 0) $inStock = 0;
		if ($price < 0) $price =0;
		if ($rating < MIN_RATING) $rating = MIN_RATING;
		if ($rating > MAX_RATING) $rating = MAX_RATING;
			$this->id = $id;
			$this->name = $name;
			$this->inStock = $inStock;
			$this->price = $price;
			$this->rating = $rating;
	}
	
	function buy()
	{
		$this->inStock--;
	}
	
	function display()
	{
		echo "name: " .$this->name. "<br>";
		echo "Items in stock: " .$this->inStock. "<br>";
		echo "Price: " .$this->price. "<br>";
		echo "Rating: " .$this->rating. "<br>";
	}
}

//Book.php
class Book  extends Media
{
	var $isbn;
	var $author;
	var $numberOfPages;
	
	function Book($id, $name, $inStock, $price, $rating,
				  $isbn, $author, $numberOfPages)
	{
		$this->Media($id, $name, $inStock, $price, $rating);
		$this->isbn = $isbn;
		$this->author = $author;
		$this->numberOfPages = $numberOfPages;
	}
	
	function display()
	{
		Media::display();
		
		echo "ISBN: ". $this->isbn. "<br>";
		echo "Author: ". $this->author. "<br>";
		echo "number of pages: ". $this->numberOfPages. "<br>";
	}
					  
}		 
		
$book = new Book(0,'PHP Programming',23,59.99,4,'124-4333-4443',
					'Ken Egervari',1024);
$book->display();
			


$message="
<fieldset><legend><font color=red>TIPS</font></legend>
    class檔案:Media.php、主程式檔:Book.php<br>
	要注意的是,我們所有的媒體在建構後都有相同的行為。所有的display()方法<br>
	都不受引數,並且會適當地顯示每一個不同媒體項目。
<br>
</fieldset>
";
echo $message."<br>";

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料