PHP5 Class and Object (一)
PHP5 release以來,最大的改變應該算是Class與Object了。它終於提供了完整的物件導向功能包括 Access modifier 與 Interface..... 等等。在此,不討論這樣改變的好與壞,作為一個程式員,我關心的是如何最快的pickup起來這個程式語言。
就先從class and object看起吧 ......
在討論詳細PHP5 Class 前先介紹一個方便的功能Autoloading Objects,當你在程式前,定義一個 function
__autoload($str) ,當程式需要new一個物件時,如果沒有include正確的檔案,則會先呼叫
_autoload(),所以,你可以這樣寫:
function __autoload($class_name) {
require_once $class_name . '.php';
}
$obj = new MyClass1();
$obj2 = new MyClass2();
?>
PHP5 定義了全新的Constructors and Destructors, Constructorl不再是與class同名的函數了。他們分別是,
void __construct([mixed args [, ...]] ) And void __denstruct(void)。
不同於Java, 當__construct被呼叫時,parent class __construct並不會自動備呼叫,若需呼叫,請自行加入parent::__construct(); __denstruct()亦是如此 。
網友在contact at tcknetwork dot com在PHP官方網站提供了以下的sample,幫助我們寫一個PHP4與PHP5通用的CLASS。
function test() {
$this->__construct();
register_shutdown_function(array($this,"__destruct"));
}
function __construct() {
echo "constructn";
}
function __destruct() {
echo "destructn";
}
};
$t=new test();
?>
基本上,這個方法在一般情況下沒有問題,但問題會發生在 如果,我在最後一行加上以下程式碼時
$t = null;
echo "This script is end heren";
?>
此時,在PHP5輸出是
construct
destruct
This script is end here
在PHP4則是
This script is end here
destruct
注意到了嗎?最後兩行輸出順序變了。
原因在於PHP5的destructor是當物件不再被參照($instance == null)或是物件被消滅(unset($instance))的時候立刻(不
同於Java的garbage collection)被呼叫。而register_shutdown_function註冊的function則是在程式結束時被呼叫。這邊其實還有一個值得注意的事情,經過我
測試的結果,當register_shutdown_function註冊一個物件中的function時,該物件是不能unset的,直到該function被call之後。參考以下例子:
class test {
function __construct() {
echo "constructn";
register_shutdown_function(array($this,"shutdown"));
}
function __destruct() {
echo "destructn";
}
function shutdown() {
echo "shutdownn";
}
};
$t=new test();
$t = null; # OR use unset($t); get the same result
echo "This script is end here";
?>
輸出為:
construct
This script is end here
shutdown
destruct
最後補充一點,PHP5為了相容PHP4的code,當他找不到__construct()時,會去者{$ClassName}()當作Constructor。可想而知,如果為了效率,寫一個專門給PHP5用的程式,最好還是使用 __construct()。
今天先說到這裡,其他的下次再說


