PHP中spl_autoload_register()和__autoload()區(qū)別分析
關于spl_autoload_register()和__autoload(),相信大多數(shù)都會選擇前者了? 看兩者的用法:
//__autoload用法
function __autoload($classname)
{
$filename = "./class/".$classname.".class.php";
if (is_file($filename))
{
include $filename;
}
}
//spl_autoload_register用法
spl_autoload_register('load_class');
function load_class($classname)
{
$filename = "./class/".$classname.".class.php";
if (is_file($filename))
{
include $filename;
}
}
使用spl_autoload_register()的好處是不可言喻的:
(1)自動加載對象更加方便,很多框架都是這樣做的:
class ClassAutoloader {
public function __construct() {
spl_autoload_register(array($this, 'loader'));
}
private function loader($className) {
echo 'Trying to load ', $className, ' via ', __METHOD__, "()\n";
include $className . '.php';
}
}
$autoloader = new ClassAutoloader();
$obj = new Class1();
$obj = new Class2();
(2)你要知道__autoload()函數(shù)只能存在一次啊,spl_autoload_register()當然能注冊多個函數(shù)
function a () {
include 'a.php';
}
function b () {
include 'b.php';
}
spl_autoload_register('a');
spl_autoload_register('b');
(3)SPL函數(shù)很豐富,提供了更多功能,如spl_autoload_unregister()注銷已經(jīng)注冊的函數(shù)、spl_autoload_functions()返回所有已經(jīng)注冊的函數(shù)等。
詳見PHP參考手冊:關于SPL函數(shù)列表.
注意:
如果在你的程序中已經(jīng)實現(xiàn)了__autoload函數(shù),它必須顯式注冊到__autoload棧中。因為
spl_autoload_register()函數(shù)會將Zend Engine中的__autoload函數(shù)取代為spl_autoload() 或 spl_autoload_call()
/**
*__autoload 方法在 spl_autoload_register 后會失效,因為 autoload_func 函數(shù)指針已指向 spl_autoload 方法
* 可以通過下面的方法來把 _autoload 方法加入 autoload_functions list
*/
spl_autoload_register( '__autoload' );
相關文章
PHP數(shù)據(jù)庫操作之基于Mysqli的數(shù)據(jù)庫操作類庫
Mysqli 是什么,我這里也不進行描述了。因為網(wǎng)上關于 Mysqli 的教程數(shù)不勝數(shù),我這里為大家介紹一款基于 Mysqli 的操作數(shù)據(jù)庫類(M.class.php)2014-04-04

