Yii2 PHP框架--自动加载函数

2016-03-30  本文已影响368人  洞房花猪

自动加载函数--__autoload()

在Yii中有spl_autoload_register() 这个自动加载函数。__autoload也是一个自动加载函数,先学习一下这个自动加载函数的用法。

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();
?>


自动加载函数--spl_autoload_register()

spl_autoload_register()是__autoload的自定义注册函数,把指定 函 数注册为__autoload。自动加载函数,作用跟魔法函数__autoload相同,当你new 一个不存在的对象时,并不会马上报错,而是执行这个函数中注 册的函数,使用这个函数的目的是是为了实现自动加载php的类,而不用每个页面都要require文件。

函数体

bool spl_autoload_register( [callable $autoload_function [, bool $throw= true [, bool $prepend= false ]]] )

参数

欲注册的自动装载函数。如果没有提供任何参数,则自动注册 autoload 的默认实现函数spl_autoload()

此参数设置了 autoload_function无法成功注册时, spl_autoload_register()是否抛出异常。

如果是 true,spl_autoload_register() 会添加函数到队列之首,而不是队列尾部。

返回值

成功时返回 **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函数。但是loadprint不会像__autoload自动触发,这时spl_autoload_register()就起作用了,它告诉PHP碰到没有定义的类就执行loadprint()。

扩展

spl_autoload_register() 调用静态的方法

举例
<? 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();
?>

扩展--反注册函数--spl_autoload_unregister()

该函数用来取消spl_autoload_register()所做的事。与注册函数相反。

函数体

bool spl_autoload_unregister(mixed $autoload_function)

参数

要注销的自动装载函数。

返回值

成功时返回 **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提供的自动装载函数栈中注销某一函数。如果该函数栈处于激活状态,并且在给定函数注销后该栈变为空,则该函数栈将会变为无效。

如果该函数注销后使得自动装载函数栈无效,即使存在有__autoload函数它也不会自动激活。


上一篇下一篇

猜你喜欢

热点阅读