一個最簡單的 PHP Class 程式例子
PHP Class 的中文一般稱為類別, Class 可以想像為資料 (Value) 與函數 (Functions) 混合的「物件」。 換言之, Class 包含資料與函數。
以下是一個最簡單的 PHP Class 例子, 只有一個資料和一個函數:
第一步是建造 Class 本身的物件。
第一步: 建造 Class 物件
<?php
class Car {
// Declare variables
// This is Value (資料)
var $tireColor;
function showTireColor( ) {
//Use $this to point to the current object.
//i.e. $this -> tireColor gets data from the variable $tireColor in the object.
echo "The color of the tires are: " . $this->tireColor;
}
}
?>
第二步: 儲存檔案
從上面的第一步, Car 的 Class 已經建造完成, 將它儲存為car_class.php 檔案, 這樣, 我們可以利用普通的 PHP 程式使用它.
第三步: 使用建造好的 Class 物件
<?php
//use include to insert the external file into script
include "car_class.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;
//Point to a variable in the object and assign value to it
$carPart -> tireColor = "Black Color";
//Call the function with the "->" operator
$carPart -> showTireColor( );
?>
第四步: 儲存檔案
將第三步的檔案儲存為 (Save As) car.php
第四步: 上傳檔案
上傳 car_class.php 和 car.php 到你的網頁寄存戶口.
第五步: 測試檔案
測試 car.php 是否可以正常執行.
瀏 灠 器 應 出 現 :
The color of car tire is: Black Color
PHP 實例:
以下是 PHP Class 的基本結構:
參考網站:
PHP Class - The Basics
http://us3.php.net/manual/en/language.oop5.basic.php