自動(dòng)加載函數(shù)--__autoload()
在Yii中有spl_autoload_register() 這個(gè)自動(dòng)加載函數(shù)。__autoload也是一個(gè)自動(dòng)加載函數(shù),先學(xué)習(xí)一下這個(gè)自動(dòng)加載函數(shù)的用法。
-
__
autoload自動(dòng)加載函數(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();
?>
- 從上面的代碼我們可以看出,當(dāng)new一個(gè)對(duì)象的時(shí)候,如果沒(méi)有引入這個(gè)類,autoload會(huì)觸發(fā),然后判斷這個(gè)類文件是否存在,如果存在的話就引入這個(gè)類文件。
自動(dòng)加載函數(shù)--spl_autoload_register()
spl_autoload_register()是
__
autoload的自定義注冊(cè)函數(shù),把指定 函 數(shù)注冊(cè)為__
autoload。自動(dòng)加載函數(shù),作用跟魔法函數(shù)__autoload相同,當(dāng)你new 一個(gè)不存在的對(duì)象時(shí),并不會(huì)馬上報(bào)錯(cuò),而是執(zhí)行這個(gè)函數(shù)中注 冊(cè)的函數(shù),使用這個(gè)函數(shù)的目的是是為了實(shí)現(xiàn)自動(dòng)加載php的類,而不用每個(gè)頁(yè)面都要require文件。
函數(shù)體
bool spl_autoload_register( [callable $autoload_function [, bool $throw= true [, bool $prepend= false ]]] )
參數(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
**。
舉例
<?php
function loadprint( $class ) {
$file = $class . '.class.php';
if (is_file($file)) {
require_once($file);
}
}
spl_autoload_register( 'loadprint' );
$obj = new PRINTIT();
$obj->doPrint();
?>
說(shuō)明
將__autoload換成loadprint函數(shù)。但是loadprint不會(huì)像__autoload自動(dòng)觸發(fā),這時(shí)spl_autoload_register()就起作用了,它告訴PHP碰到?jīng)]有定義的類就執(zhí)行l(wèi)oadprint()。
擴(kuò)展
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();
?>
擴(kuò)展--反注冊(cè)函數(shù)--spl_autoload_unregister()
該函數(shù)用來(lái)取消spl_autoload_register()所做的事。與注冊(cè)函數(shù)相反。
函數(shù)體
bool spl_autoload_unregister(mixed $autoload_function)
參數(shù)
-
$autoload_function
要注銷的自動(dòng)裝載函數(shù)。
返回值
成功時(shí)返回 **TRUE
**, 或者在失敗時(shí)返回 **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'));
說(shuō)明
從spl提供的自動(dòng)裝載函數(shù)棧中注銷某一函數(shù)。如果該函數(shù)棧處于激活狀態(tài),并且在給定函數(shù)注銷后該棧變?yōu)榭眨瑒t該函數(shù)棧將會(huì)變?yōu)闊o(wú)效。
如果該函數(shù)注銷后使得自動(dòng)裝載函數(shù)棧無(wú)效,即使存在有__autoload函數(shù)它也不會(huì)自動(dòng)激活。