(PHP 5 >= 5.1.0, PHP 7, PHP 8)
spl_autoload_register — 注冊給定的函數(shù)作為 __autoload 的實現(xiàn)
$autoload_function
= ?, bool $throw
= true, bool $prepend
= false): bool將函數(shù)注冊到SPL __autoload函數(shù)隊列中。如果該隊列中的函數(shù)尚未激活,則激活它們。
如果在你的程序中已經(jīng)實現(xiàn)了__autoload()函數(shù),它必須顯式注冊到__autoload()隊列中。因為 spl_autoload_register()函數(shù)會將Zend Engine中的__autoload()函數(shù)取代為spl_autoload()或spl_autoload_call()。
如果需要多條 autoload 函數(shù),spl_autoload_register() 滿足了此類需求。 它實際上創(chuàng)建了 autoload 函數(shù)的隊列,按定義時的順序逐個執(zhí)行。相比之下, __autoload() 只可以定義一次。
autoload_function
欲注冊的自動裝載函數(shù)。如果沒有提供任何參數(shù),則自動注冊 autoload 的默認(rèn)實現(xiàn)函數(shù)spl_autoload()。
throw
此參數(shù)設(shè)置了 autoload_function
無法成功注冊時,
spl_autoload_register()是否拋出異常。
prepend
如果是 true,spl_autoload_register() 會添加函數(shù)到隊列之首,而不是隊列尾部。
成功時返回 true
, 或者在失敗時返回 false
。
版本 | 說明 |
---|---|
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 起可以使用一個匿名函數(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;
?>
以上例程的輸出類似于:
[[Foobar\InexistentClass]] Fatal error: Class 'Foobar\InexistentClass' not found in ...