码迷,mamicode.com
首页 > 其他好文 > 详细

_autoload 自动加载类和spl_autoload_register()函数

时间:2017-08-20 14:06:55      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:body   未定义   img   new   too   实例   引入   nbsp   加载   

  新建一个类文件名字自己随便去:news类在auto.php文件里面去实例news类而没有引入该类,可以用_autoload自动加载方法类去处理.

  news.class.php文件

class news{ 
    function do_new() {
        echo ‘aaa‘;
    }
}

  auto.php文件使用_autoload函数要定义函数体自己去定义

技术分享
function __autoload( $class ) {
    $file = $class . ‘.class.php‘;
    if ( is_file($file) ) {
        require_once($file);
    }
} 
$obj = new news();
$obj->do_new();
技术分享

二、spl_autoload_register()这个函数(PHP 5 >= 5.1.2)与__autoload有与曲同工之妙,通过加载自己建的函数里面处理加载文件,但是文件变量可以自动加入参数

  动态:实例调用的文件还是news.class.php实例化,spl_autoload文件如下:

技术分享
function load($class){ //定义引用文件的函数
    $file = $class . ‘.class.php‘;  
    if (is_file($file)) {  
        require_once($file);  
    }
}
spl_autoload_register( ‘load‘ ); //调用自己定义的load函数
$obj = new news();
$obj->do_new();
技术分享

  静态:spl_autoload_register() 调用静态方法

技术分享
class n_static {
    public static function load( $class ) {
        $file = $class . ‘.class.php‘;  
        if(is_file($file)) {  
            require_once($file);  
        } 
    }
} 
spl_autoload_register(  array(‘n_static‘,‘load‘)  );
//另一种写法:spl_autoload_register(  "n_static::load"  ); 
$obj = new news();
$obj->do_new();

_autoload 自动加载类和spl_autoload_register()函数

标签:body   未定义   img   new   too   实例   引入   nbsp   加载   

原文地址:http://www.cnblogs.com/ZJCD/p/7399745.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!