PHP 網頁程式設計課程目錄

再一個簡單的 PHP Class 程式例子

再來一個簡單的 PHP Class 例子, 和先前的兩個例子差不多, 這例子用了兩個 Arguments。

第一步也是建造 Class 本身的物件。

第一步: 建造 Class 物件

<?php


class Car {
     // Declare variables
     // Use to store the color and Model of tire
     var $tireColor;
     var $tireModel;

function showTire($color_of_tire, $model_of_tire) {
     //Use $this to point to the current object.
     //i.e. $this -> tireColor gets data of $color_of_tire
     echo "The color of the tire is: " . $this -> tireColor = $color_of_tire;
     echo "<br />";
     echo "The Model of car tire is: " . $this -> tireModel = $model_of_tire;
}


}
?>

第二步: 儲存檔案

從上面的第一步, Car 的 Class 已經建造完成, 將它儲存為car_class_3.php 檔案, 這樣, 我們可以利用普通的 PHP 程式使用它.

第三步: 使用建造好的 Class 物件

<?php


//use include to insert the external file into script
include "car_class_3.php";

//Declare to create a new copy of object to work into
//The new copy is stored in the $carPart variable
//產生了一個叫做 $carPart 的Car 類別的物件
$carPart = new Car;


//Call the function with the "->" operator
//This time with the argument "Black Color"
$carPart -> showTire("Red Color", "Bridge-Stone-NM");

?>

第四步: 儲存檔案

將第三步的檔案儲存為 (Save As) car_3.php

第四步: 上傳檔案

上傳 car_class_3.php 和 car_3.php 到你的網頁寄存戶口.

第五步: 測試檔案

測試 car_3.php 是否可以正常執行.

瀏 灠 器 應 出 現 :

The Color of car tire is: Black Color
The Model of car tire is: Bridge-Stone-NM


PHP 實例:

View PHP Example