spl_autoload_register
(PHP 5 >= 5.1.2)
spl_autoload_register — 注冊__autoload()函數(shù)
說明
bool spl_autoload_register ([ callback $autoload_function ] )
將函數(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()。
參數(shù)
autoload_function
欲注冊的自動裝載函數(shù)。如果沒有提供任何參數(shù),則自動注冊autoload的默認(rèn)實現(xiàn)函數(shù) spl_autoload()。
返回值
如果成功則返回 TRUE,失敗則返回 FALSE。
注:SPL是Standard PHP Library(標(biāo)準(zhǔn)PHP庫)的縮寫。它是PHP5引入的一個擴展庫,其主要功能包括autoload機制的實現(xiàn)及包括各種Iterator接口或類。 SPL autoload機制的實現(xiàn)是通過將函數(shù)指針autoload_func指向自己實現(xiàn)的具有自動裝載功能的函數(shù)來實現(xiàn)的。SPL有兩個不同的函數(shù) spl_autoload, spl_autoload_call,通過將autoload_func指向這兩個不同的函數(shù)地址來實現(xiàn)不同的自動加載機制。
范例
設(shè)我們有一個類文件A.php,里面定義了一個名字為A的類:
- <?php
- class A
- {
- public function __construct()
- {
- echo 'Got it.';
- }
- }
- <?php
- class A
- {
- public function __construct()
- {
- echo 'Got it.';
- }
- }
然后我們有一個index.php需要用到這個類A,常規(guī)的寫法就是
- <?php
- require('A.php');
- $a = new A();
- <?php
- require('A.php');
- $a = new A();
但是有一個問題就是,假如我們的index.php需要包含的不只是類A,而是需要很多類,這樣子就必須寫很多行require語句,有時候也會讓人覺得不爽。
不過在php5之后的版本,我們就不再需要這樣做了。在php5中,試圖使用尚未定義的類時會自動調(diào)用__autoload函數(shù),所以我們可以通過編寫__autoload函數(shù)來讓php自動加載類,而不必寫一個長長的包含文件列表。
例如在上面那個例子中,index.php可以這樣寫:
- <?php
- function __autoload($class)
- {
- $file = $class . '.php';
- if (is_file($file)) {
- require_once($file);
- }
- }
- $a = new A();
- //Vevb.com
- <?php
- function __autoload($class)
- {
- $file = $class . '.php';
- if (is_file($file)) {
- require_once($file);
- }
- }
- $a = new A();
當(dāng)然上面只是最簡單的示范,__autoload只是去include_path尋找類文件并加載,我們可以根據(jù)自己的需要定義__autoload加載類的規(guī)則。
此外,假如我們不想自動加載的時候調(diào)用__autoload,而是調(diào)用我們自己的函數(shù)(或者類方法),我們可以使用spl_autoload_register來注冊我們自己的autoload函數(shù)。它的函數(shù)原型如下:
bool spl_autoload_register ( [callback $autoload_function] )
我們繼續(xù)改寫上面那個例子:
- <?php
- function loader($class)
- {
- $file = $class . '.php';
- if (is_file($file)) {
- require_once($file);
- }
- }
- spl_autoload_register('loader');
- $a = new A();
- <?php
- function loader($class)
- {
- $file = $class . '.php';
- if (is_file($file)) {
- require_once($file);
- }
- }
- spl_autoload_register('loader');
- $a = new A();
這樣子也是可以正常運行的,這時候php在尋找類的時候就沒有調(diào)用__autoload而是調(diào)用我們自己定義的函數(shù)loader了。同樣的道理,下面這種寫法也是可以的:
- <?php
- class Loader
- {
- public static function loadClass($class)
- {
- $file = $class . '.php';
- if (is_file($file)) {
- require_once($file);
- }
- }
- }
- spl_autoload_register(array('Loader', 'loadClass'));
- $a = new A();
|
新聞熱點
疑難解答