PHP自动加载spl_autoload_register()
生活随笔
收集整理的這篇文章主要介紹了
PHP自动加载spl_autoload_register()
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
__autoload
printit.class.php
<?php class PRINTIT {function doPrint() {echo 'hello world';} }index.php
<? function __autoload( $class ) {$file = $class . '.class.php';if ( is_file($file) ) {require_once($file);} } $obj = new PRINTIT(); $obj->doPrint(); 運行index.php后正常輸出hello world。在index.php中, 由于沒有包含printit.class.php,在實例化printit時, 自動調用__autoload函數,參數$class的值即為類名printit, 此時printit.class.php就被引進來了。在面向對象中這種方法經常使用,可以避免書寫過多的引用文件, 同時也使整個系統更加靈活。spl_autoload_register()
<? function loadprint( $class ) {$file = $class . '.class.php';if (is_file($file)) {require_once($file);} } spl_autoload_register( 'loadprint' ); $obj = new PRINTIT(); $obj->doPrint();?>將__autoload換成loadprint函數。但是loadprint不會像__autoload自動觸發,這時spl_autoload_register()就起作用了,它告訴PHP碰到沒有定義的類就執行loadprint()。
spl_autoload_register() 調用靜態方法
<? class test {public static function loadprint( $class ) {$file = $class . '.class.php';if (is_file($file)) {require_once($file);}} } spl_autoload_register( array('test','loadprint') ); //另一種寫法:spl_autoload_register( "test::loadprint" ); $obj = new PRINTIT(); $obj->doPrint();?>spl_autoload_register()分析
spl_autoload_register — 注冊__autoload()函數 說明 bool spl_autoload_register ([ callback $autoload_function ] ) 將函數注冊到SPL __autoload函數棧中。如果該棧中的函數尚未激活,則激活它們。 如果在你的程序中已經實現了__autoload函數,它必須顯式注冊到__autoload棧中。 因為spl_autoload_register()函數會將 Zend Engine中的__autoload函數取代為spl_autoload() 或 spl_autoload_call()。參數 autoload_function 欲注冊的自動裝載函數。如果沒有提供任何參數, 則自動注冊autoload的默認實現函數spl_autoload()返回值 如果成功則返回 TRUE,失敗則返回 FALSE。 classLOAD {staticfunctionloadClass($class_name){$filename= $class_name.".class.php";$path= "include/".$filenameif(is_file($path)) returninclude$path;} } /*** 設置對象的自動載入* spl_autoload_register — Register given function as __autoload() implementation*/ spl_autoload_register(array('LOAD', 'loadClass')); /** *__autoload 方法在 spl_autoload_register 后會失效,因為 autoload_func 函數指針已指向 spl_autoload 方法 * 可以通過下面的方法來把 _autoload 方法加入 autoload_functions list */ spl_autoload_register( '__autoload');總結
以上是生活随笔為你收集整理的PHP自动加载spl_autoload_register()的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL主从复制延时方法
- 下一篇: 30岁了想学一门技术回家开店(30岁了想