PHP基礎(chǔ)之類和對(duì)象4——自動(dòng)加載對(duì)象
很多開發(fā)者寫面向?qū)ο蟮膽?yīng)用程序時(shí)對(duì)每個(gè)類的定義建立一個(gè) PHP 源文件。一個(gè)很大的煩惱是不得不在每個(gè)腳本開頭寫一個(gè)長長的包含文件列表(每個(gè)類一個(gè)文件)。
在 PHP 5 中,不再需要這樣了。可以定義一個(gè)?__autoload()?函數(shù),它會(huì)在試圖使用尚未被定義的類時(shí)自動(dòng)調(diào)用。通過調(diào)用此函數(shù),腳本引擎在 PHP 出錯(cuò)失敗前有了最后一個(gè)機(jī)會(huì)加載所需的類。
Tip
spl_autoload_register()?提供了一種更加靈活的方式來實(shí)現(xiàn)類的自動(dòng)加載。因此,不再建議使用?__autoload()?函數(shù),在以后的版本中它可能被棄用。
Note:
在 5.3.0 版之前,__autoload 函數(shù)拋出的異常不能被?catch?語句塊捕獲并會(huì)導(dǎo)致一個(gè)致命錯(cuò)誤。從 5.3.0+ 之后,__autoload 函數(shù)拋出的異常可以被?catch?語句塊捕獲,但需要遵循一個(gè)條件。如果拋出的是一個(gè)自定義異常,那么必須存在相應(yīng)的自定義異常類。__autoload 函數(shù)可以遞歸的自動(dòng)加載自定義異常類。
Note:
自動(dòng)加載不可用于 PHP 的 CLI?交互模式。
Example #1 自動(dòng)加載示例
本例嘗試分別從 MyClass1.php 和 MyClass2.php 文件中加載?MyClass1?和?MyClass2?:
function __autoload($class_name){
require_once $class_name.’.php’;
}
$obj = new MyClass1();
$obj2 = new MyClass2();
注意:MyClass1.php和MyClass2.php需要和當(dāng)前腳本在同一目錄才能加載到
Example #2 另一個(gè)例子
本例嘗試加載接口?ITest:
function?__autoload($name) {
???var_dump($name);
}
class?Foo?implements?ITest?{
}
/*
string(5) 'ITest'
Fatal error: Interface ’ITest’ not found in ...
*/
Example #3 自動(dòng)加載在 PHP 5.3.0+ 中的異常處理
本例拋出一個(gè)異常并在 try/catch 語句塊中演示。
function?__autoload($name) {
???echo?'Want to load?$name.n';
???throw new?Exception('Unable to load?$name.');
}
try {
???$obj?= new?NonLoadableClass();
} catch (Exception $e) {
???echo?$e->getMessage(),?'n';
}
以上例程會(huì)輸出:
Want to load NonLoadableClass.Unable to load NonLoadableClass.
Example #4 自動(dòng)加載在 PHP 5.3.0+ 中的異常處理 - 沒有自定義異常機(jī)制
本例將一個(gè)異常拋給不存在的自定義異常處理函數(shù)。
以上例程會(huì)輸出:
Want to load NonLoadableClass.Want to load MissingException.Fatal error: Class ’MissingException’ not found in testMissingException.php on line 4
了解更多參見unserialize()
unserialize_callback_func
spl_autoload()
spl_autoload_register()
相關(guān)文章:
1. ASP.NET MVC遍歷驗(yàn)證ModelState的錯(cuò)誤信息2. 將properties文件的配置設(shè)置為整個(gè)Web應(yīng)用的全局變量實(shí)現(xiàn)方法3. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說明4. jsp網(wǎng)頁實(shí)現(xiàn)貪吃蛇小游戲5. 用css截取字符的幾種方法詳解(css排版隱藏溢出文本)6. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向7. asp中response.write("中文")或者js中文亂碼問題8. PHP設(shè)計(jì)模式中工廠模式深入詳解9. CSS hack用法案例詳解10. ThinkPHP5實(shí)現(xiàn)JWT Token認(rèn)證的過程(親測(cè)可用)
