與 class 同名的 member function 即為 constructor (建構子),constructor 在物件生成時自動執行,例如:
<?php class Shopping extends Cart { var $customer, $telephone;
function Shopping() { $this->customer = "GUEST"; $this->telephone = "UNKNOW"; }
function person($name, $tel) { $this->customer = $name; $this->telephone = $tel } } ?>
Shopping 類別的物件生成時,Shopping 建構子會自動被執行:
$shopping = new $Shopping;
此時 $shopping->customer 與 $shopping->telephone 分別為 "GUEST" 與 "UNKNOW",除非利用 person() 重新給定 customer 與 telephone 的值,否則這兩個 member data 的值不會改變。
這裡的 constructor 還有另外一種較具彈性的寫法:
<?php class Shopping extends Cart { var $customer, $telephone;
function Shopping($name = "GUEST", $tel = $"UNKNOWN") { $this->customer = $name; $this->telephone = $tel"; } } ?>
生成物件時,有 2 種不同的情況:
1.
$shopping = new Shopping;
此時 $shopping->customer 與 $shopping->telephone 一樣為 "GUEST" 與 "UNKNOWN"。
2.
$shopping = new Shopping("Jollen", "123456789");
指定參數給建構子,此時 $shopping->customer 與 $shopping->telephone 分別為 "Jollen" 與 "123456789"。
在 PHP 4 的 class 裡只能對 var 變數做常數初始化的動作,因此底下的寫法是錯誤的:
class Cart { var $shop = "Aloud Company"; var $items = array("Mouse", "Keyboard"); }
對變數給定非常數 (non-constant) 值時,必須將給值的動作寫在 constructor 函數裡才可以。因此上面的範例應該改寫成底下的寫法:
<?php
class Cart { var $shop; var $items;
function Cart() { $this->shop = "Aloud Company"; $this->items = array("Mouse", "Keyboard"); } } ?>
在 PHP 4 裡,constructor 還有一個重要的特性。當 class 裡沒有 constructor 時,則 base class 的 constructor 會被呼叫。請看底下的範例:
<?php
class base_cart { function base_cart() { echo "Shopping cart is based on PHP."; } }
class Cart extends base_cart { var $shop; var $items;
function init() { $this->shop = "Aloud Company"; $this->items = array("Mouse", "Keyboard"); } }
$cart = new Cart;
?>
輸出結果:
Shopping cart is based on PHP.
由於 Cart 類別本身沒有 constructor,因此當 $cart 生成時,就會呼叫 base class 即 base_cart 類別的 constructor。假如 base class 也沒有 constructor,則當 $cart 生成時,就不會有任何 constructor 被呼叫。
--jollen