詳解PHP文件的自動加載(autoloading)
傳統(tǒng)上,在PHP里,當(dāng)我們要用到一個class文件的時候,我們都得在文檔頭部require或者include一下:
<?php
require_once('../includes/functions.php');
require_once('../includes/database.php');
require_once('../includes/user.php');
...
但是一旦要調(diào)用的文檔多了,就得每次都寫一行,瞅著也不美觀,有什么辦法能讓PHP文檔自動加載呢?
<?php
function __autoload($class_name)
{
require "./{$class_name}.php";
}
對,可以使用PHP的魔法函數(shù)__autoload(),上面的示例就是自動加載當(dāng)前目錄下的PHP文件。當(dāng)然,實(shí)際當(dāng)中,我們更可能會這么來使用:
<?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");
}
}
也即是做了一定的文件名大小寫處理,然后在require之前檢查文件是否存在,不存在的話顯示自定義的信息。
類似用法經(jīng)常在私人項(xiàng)目,或者說是單一項(xiàng)目的框架中見到,為什么呢?因?yàn)槟阒荒芏x一個__autoload function,在多人開發(fā)中,做不到不同的developer使用不同的自定義的autoloader,除非大家都提前說好了,都使用一個__autoload,涉及到改動了就進(jìn)行版本同步,這很麻煩。
也主要是因?yàn)榇?,有個好消息,就是這個__autoload函數(shù)馬上要在7.2版本的PHP中棄用了。
Warning This feature has been DEPRECATED as of PHP 7.2.0. Relying on this feature is highly discouraged.
那么取而代之的是一個叫spl_autoload_register()的東東,它的好處是可以自定義多個autoloader.
//使用匿名函數(shù)來autoload
spl_autoload_register(function($class_name){
require_once('...');
});
//使用一個全局函數(shù)
function Custom()
{
require_once('...');
}
spl_autoload_register('Custom');
//使用一個class當(dāng)中的static方法
class MyCustomAutoloader
{
static public function myLoader($class_name)
{
require_once('...');
}
}
//傳array進(jìn)來,第一個是class名,第二個是方法名
spl_autoload_register(['MyCustomAutoloader','myLoader']);
//甚至也可以用在實(shí)例化的object上
class MyCustomAutoloader
{
public function myLoader($class_name)
{
}
}
$object = new MyCustomAutoloader;
spl_autoload_register([$object,'myLoader']);
值得一提的是,使用autoload,無論是__autoload(),還是spl_autoload_register(),相比于require或include,好處就是autoload機(jī)制是lazy loading,也即是并不是你一運(yùn)行就給你調(diào)用所有的那些文件,而是只有你用到了哪個,比如說new了哪個文件以后,才會通過autoload機(jī)制去加載相應(yīng)文件。
當(dāng)然,laravel包括各個package里也是經(jīng)常用到spl_autoload_register,比如這里:
/**
* Prepend the load method to the auto-loader stack.
*
* @return void
*/
protected function prependToLoaderStack()
{
spl_autoload_register([$this, 'load'], true, true);
}
相關(guān)文章
PHP7.1中使用openssl替換mcrypt的實(shí)例詳解
這篇文章主要介紹了PHP7.1中使用openssl替換mcrypt的實(shí)例詳解,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2018-07-07
ZendFramework框架實(shí)現(xiàn)連接兩個或多個數(shù)據(jù)庫的方法
這篇文章主要介紹了ZendFramework框架實(shí)現(xiàn)連接兩個或多個數(shù)據(jù)庫的方法,涉及ZendFramework框架配置文件與數(shù)據(jù)庫操作相關(guān)技巧,需要的朋友可以參考下2016-12-12
destoon網(wǎng)站轉(zhuǎn)移服務(wù)器后搜索漢字出現(xiàn)亂碼的解決方法
這篇文章主要介紹了destoon網(wǎng)站轉(zhuǎn)移服務(wù)器后搜索漢字出現(xiàn)亂碼的解決方法,非常實(shí)用,需要的朋友可以參考下2014-06-06

