spl_autoload_register

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

spl_autoload_register注冊(cè)給定的函數(shù)作為 __autoload 的實(shí)現(xiàn)

說(shuō)明

spl_autoload_register(callable $autoload_function = ?, bool $throw = true, bool $prepend = false): bool

將函數(shù)注冊(cè)到SPL __autoload函數(shù)隊(duì)列中。如果該隊(duì)列中的函數(shù)尚未激活,則激活它們。

如果在你的程序中已經(jīng)實(shí)現(xiàn)了__autoload()函數(shù),它必須顯式注冊(cè)到__autoload()隊(duì)列中。因?yàn)? spl_autoload_register()函數(shù)會(huì)將Zend Engine中的__autoload()函數(shù)取代為spl_autoload()spl_autoload_call()。

如果需要多條 autoload 函數(shù),spl_autoload_register() 滿足了此類(lèi)需求。 它實(shí)際上創(chuàng)建了 autoload 函數(shù)的隊(duì)列,按定義時(shí)的順序逐個(gè)執(zhí)行。相比之下, __autoload() 只可以定義一次。

參數(shù)

autoload_function

欲注冊(cè)的自動(dòng)裝載函數(shù)。如果沒(méi)有提供任何參數(shù),則自動(dòng)注冊(cè) autoload 的默認(rèn)實(shí)現(xiàn)函數(shù)spl_autoload()。

throw

此參數(shù)設(shè)置了 autoload_function 無(wú)法成功注冊(cè)時(shí), spl_autoload_register()是否拋出異常。

prepend

如果是 true,spl_autoload_register() 會(huì)添加函數(shù)到隊(duì)列之首,而不是隊(duì)列尾部。

返回值

成功時(shí)返回 true, 或者在失敗時(shí)返回 false。

更新日志

版本 說(shuō)明
5.3.0 引入了命名空間的支持。
5.3.0 添加了 prepend 參數(shù)。

范例

示例 #1 spl_autoload_register() 作為 __autoload() 函數(shù)的替代

<?php

// function __autoload($class) {
//     include 'classes/' . $class . '.class.php';
// }

function my_autoloader($class) {
    include 
'classes/' $class '.class.php';
}

spl_autoload_register('my_autoloader');

// 或者,自 PHP 5.3.0 起可以使用一個(gè)匿名函數(shù)
spl_autoload_register(function ($class) {
    include 
'classes/' $class '.class.php';
});

?>

示例 #2 class 未能加載的 spl_autoload_register() 例子

<?php

namespace Foobar;

class 
Foo {
    static public function 
test($name) {
        print 
'[['$name .']]';
    }
}

spl_autoload_register(__NAMESPACE__ .'\Foo::test'); // 自 PHP 5.3.0 起

new InexistentClass;

?>

以上例程的輸出類(lèi)似于:

[[Foobar\InexistentClass]]
Fatal error: Class 'Foobar\InexistentClass' not found in ...

參見(jiàn)