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

 一、_autoload 自动加载类:当我们实例化一个未定义的类时,就会触此函数。到了php7.1以后版本不支持此函数好像抛弃了

  新建一个类文件名字自己随便去: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();
原文地址:https://www.cnblogs.com/ZJCD/p/7399745.html