自動加載函數(shù)--__autoload()
在Yii中有spl_autoload_register() 這個自動加載函數(shù)。__autoload也是一個自動加載函數(shù),先學習一下這個自動加載函數(shù)的用法。
-
__
autoload自動加載函數(shù)
printit.class.php
<?php
class PRINTIT {
function doPrint() {
echo 'hello world';
}
}
?>
index.php
<?php
function __autoload( $class ) {
$file = $class . '.class.php';
if ( is_file($file) ) {
require_once($file);
}
}
$obj = new PRINTIT();
$obj->doPrint();
?>
- 從上面的代碼我們可以看出,當new一個對象的時候,如果沒有引入這個類,autoload會觸發(fā),然后判斷這個類文件是否存在,如果存在的話就引入這個類文件。
自動加載函數(shù)--spl_autoload_register()
spl_autoload_register()是
__
autoload的自定義注冊函數(shù),把指定 函 數(shù)注冊為__
autoload。自動加載函數(shù),作用跟魔法函數(shù)__autoload相同,當你new 一個不存在的對象時,并不會馬上報錯,而是執(zhí)行這個函數(shù)中注 冊的函數(shù),使用這個函數(shù)的目的是是為了實現(xiàn)自動加載php的類,而不用每個頁面都要require文件。
函數(shù)體
bool spl_autoload_register( [callable $autoload_function [, bool $throw= true [, bool $prepend= false ]]] )
參數(shù)
-
autoload_function
欲注冊的自動裝載函數(shù)。如果沒有提供任何參數(shù),則自動注冊 autoload 的默認實現(xiàn)函數(shù)spl_autoload()。
-
$throw
此參數(shù)設置了 autoload_function無法成功注冊時, spl_autoload_register()是否拋出異常。
-
$prepend
如果是 true,spl_autoload_register() 會添加函數(shù)到隊列之首,而不是隊列尾部。
返回值
成功時返回 **TRUE
**, 或者在失敗時返回 **FALSE
**。
舉例
<?php
function loadprint( $class ) {
$file = $class . '.class.php';
if (is_file($file)) {
require_once($file);
}
}
spl_autoload_register( 'loadprint' );
$obj = new PRINTIT();
$obj->doPrint();
?>
說明
將__autoload換成loadprint函數(shù)。但是loadprint不會像__autoload自動觸發(fā),這時spl_autoload_register()就起作用了,它告訴PHP碰到?jīng)]有定義的類就執(zhí)行l(wèi)oadprint()。
擴展
spl_autoload_register() 調(diào)用靜態(tài)的方法
舉例
<? php
class test {
public static function loadprint( $class ) {
$file = $class . '.class.php';
if (is_file($file)) {
require_once($file);
}
}
}
spl_autoload_register( array('test','loadprint') );
//另一種寫法:spl_autoload_register( "test::loadprint" );
$obj = new PRINTIT();
$obj->doPrint();
?>
擴展--反注冊函數(shù)--spl_autoload_unregister()
該函數(shù)用來取消spl_autoload_register()所做的事。與注冊函數(shù)相反。
函數(shù)體
bool spl_autoload_unregister(mixed $autoload_function)
參數(shù)
-
$autoload_function
要注銷的自動裝載函數(shù)。
返回值
成功時返回 **TRUE
**, 或者在失敗時返回 **FALSE
**。
舉例
$functions = spl_autoload_functions();
foreach($functions as $function)
{
spl_autoload_unregister($function);
}
<?php
spl_autoload_register(array('Doctrine', 'autoload'));// some process
spl_autoload_unregister(array('Doctrine', 'autoload'));
說明
從spl提供的自動裝載函數(shù)棧中注銷某一函數(shù)。如果該函數(shù)棧處于激活狀態(tài),并且在給定函數(shù)注銷后該棧變?yōu)榭眨瑒t該函數(shù)棧將會變?yōu)闊o效。
如果該函數(shù)注銷后使得自動裝載函數(shù)棧無效,即使存在有__autoload函數(shù)它也不會自動激活。