PHP进阶学习之spl_autoload_register与__autoload方法使用


spl_autoload_register()函数应该是主流框架使用最多的也是非常核心的函数之一,可实现自动注册函数和类,实现类似__autoload() 函数功能,简化了类的调用与加载,提高了工作的效率。

支持版本:PHP 5 >= 5.1.2

至于效率问题。php手册上有如此之话:

bool spl_autoload_register ([ callback$autoload_function ] )

将函数注册到SPL __autoload函数栈中。如果该栈中的函数尚未激活,则激活它们。如果在你的程序中已经实现了__autoload函数,它必须显式注册到__autoload栈中。因为spl_autoload_register()函数会将Zend Engine中的__autoload函数取代为spl_autoload()或spl_autoload_call()。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
class autoload
{
   public static function load( $class name )
   {
     $filename = $classname . ".class.php" ;
     if ( file_exists ( $filename )) {
       require_once $filename ;
     }
   }
}
 
function __autoload( $class name )
{
     // 这个是默认的 autoload 方法
     $filename = $classname . ".class.php" ;
     if ( file_exists ( $filename )) {
       require_once $filename ;
     }
}
 
// 注册一个 autoloader
spl_autoload_register( 'autoload::load' );
spl_autoload_register( '__autoload' );
  // 注:下面的类看上去没有定义,但其实系统根据sql_autoload_register提供的路径会自动去搜索
//foo.class.php文件,如果没找到才报错。
$foo = new foo();
$foo ->bar();
?>

在补充下:
__autoload 方法在 spl_autoload_register 后会失效,因为 autoload_func 函数指针已指向 spl_autoload 方法
* 可以通过下面的方法来把 _autoload 方法加入 autoload_functions list

spl_autoload_register( '__autoload' );

此外我们还可以使用我们自定义的加载方法:

第一种函数式:

1
2
3
4
5
6
7
8
9
10
11
function my_own_loader( $classname )
{
     $class_file = strtolower ( $classname ). ".php" ;
     if ( file_exists ( $class_file )){
         require_once ( $class_file );
     }
}
 
spl_autoload_register( "my_own_loader" );
 
$a = new A();

第二种类式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Loader
{
     public static function my_own_loader( $classname )
     {
         $class_file = strtolower ( $classname ). ".php" ;
         if ( file_exists ( $class_file )){
             require_once ( $class_file );
         }
     }
}
 
// 通过数组的形式传递类和方法的名称
spl_autoload_register( array ( "my_own_loader" , "Loader" ));
$a = new A();

实例:CI框架实现类加载的同时,其对应的model也生成。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
static public function myAutoload( $class ){
   if ( file_exists (APPPATH. 'models' .DIRECATORY_SEPARATOR. $class . '.php' )){
      require_once APPPATH. 'models' .DIRECATORY_SEPARATOR. $class . '.php' ;
   }
}
/**
* 注册加载器
*/
static public function autoload(){
    spl_autoload_register( array ( __CLASS__ , 'myAutoload' ));
    if ( class_exists ( '__autoload' )){
       spl_autoload_register( '__autoload' );
    }
}
MY_Controller::autoload();

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值