PHP的自动加载__autoload spl_autoload_register
生活随笔
收集整理的這篇文章主要介紹了
PHP的自动加载__autoload spl_autoload_register
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
https://www.jb51.net/article/134372.htm
問題
傳統(tǒng)上,在PHP里,當我們要用到一個class文件的時候,我們都得在文檔頭部require或者include一下: <?php require_once('../includes/functions.php'); require_once('../includes/database.php'); require_once('../includes/user.php'); ... 但是一旦要調用的文檔多了,就得每次都寫一行,瞅著也不美觀,有什么辦法能讓PHP文檔自動加載呢?方法:使用__autoload
<?php function __autoload($class_name) {require "./{$class_name}.php"; } 對,可以使用PHP的魔法函數(shù)__autoload(),上面的示例就是自動加載當前目錄下的PHP文件。 當然,實際當中,我們更可能會這么來使用:<?php function __autoload($class_name) {$name = strtolower($class_name);$path = "../includes/{$name}.php";if(file_exists($path)){require_once($path);}else{die("the file {$class_name} could not be found");} }__autoload存在的問題:做不到多個開發(fā)人員使用不同的自定義的autoloader, 除非大家都提前說好了,都使用一個__autoload,涉及到改動了就進行版本同步,這很麻煩。 __autoload函數(shù)馬上要在7.2版本的PHP中棄用了。 取而代之的是一個叫spl_autoload_register()的東東,它的好處是可以自定義多個autoloader.方法二:spl_autoload_register
如果需要多條 autoload 函數(shù),spl_autoload_register() 滿足了此類需求。 它實際上創(chuàng)建了 autoload 函數(shù)的隊列,按定義時的順序逐個執(zhí)行。 相比之下, __autoload() 只可以定義一次。 autoload_function 欲注冊的自動裝載函數(shù)。如果沒有提供任何參數(shù),則自動注冊 autoload 的默認實現(xiàn)函數(shù)spl_autoload()。 throw 此參數(shù)設置了 autoload_function 無法成功注冊時, spl_autoload_register()是否拋出異常。 prepend 如果是 true,spl_autoload_register() 會添加函數(shù)到隊列之首,而不是隊列尾部。 //使用一個全局函數(shù) function Custom() {require_once('...'); } spl_autoload_register('Custom');//使用一個class當中的static方法 class MyCustomAutoloader {static public function myLoader($class_name){require_once('...'); } } //傳array進來,第一個是class名,第二個是方法名 spl_autoload_register(['MyCustomAutoloader','myLoader']);//甚至也可以用在實例化的object上 class MyCustomAutoloader {public function myLoader($class_name){} } $object = new MyCustomAutoloader; spl_autoload_register([$object,'myLoader']);使用autoload,無論是__autoload(),還是spl_autoload_register(),相比于require或include, 好處就是autoload機制是lazy loading,也即是并不是你一運行就給你調用所有的那些文件,而是只有你 用到了哪個,比如說new了哪個文件以后,才會通過autoload機制去加載相應文件。總結
__autoload只可以定義一次,加載引用的函數(shù)直接寫在__autoload(){}里面
spl_autoload_register可以定義多次,并且可以引用自定義的加載引用類的函數(shù),相當與有一個加載函數(shù)的隊列,而上面的函數(shù)只允許一個,不夠靈活強大!
總結
以上是生活随笔為你收集整理的PHP的自动加载__autoload spl_autoload_register的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 系统软件包括哪些方面(系统软件包括哪些)
- 下一篇: PHP的break与continue