使用spl_autoload_register实现自动加载

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

第一步.实现自动加载函数

 <?php 
function load(){ 
require_once 'lib.php'; 
} 
spl_autoload_register('load'); 
?> 

 lib.php代码

 
<?php 
class className{ 
function method(){ 
echo 'a method in class'; 
} 
} 

function onlyMethod(){ 
echo 'method only'; 
} 
?> 

 第二步.调用自动加载类

 $class = new className(); 
$class->method(); 
onlyMethod(); 

 输出:
a method in class
method only

第三步,直接调用函数

onlyMethod();

说明:没有实例化类,直接调用lib.php文件中的onlyMethod()函数
输出:
Fatal error: Call to undefined function onlyMethod() in '...(省略路径)'

第四步,实例化className类,再直接调用

$class = new className();
onlyMethod();

输出:method only

从上面的四步实验发现,如果加载的文件包含函数,使用则一定需要实例化里面的类,否则就产生异常情况 Call to undefined function错误,具体在使用中要注意一下。

 

THINKPHP中的类自动导入功能

/Lib/Think/Core/App.class.php line62

// 允许注册AUTOLOAD方法
if(C('APP_AUTOLOAD_REG') && function_exists('spl_autoload_register'))
 spl_autoload_register(array('Think', 'autoload'));

 /Lib/Think/Core/Think.class.php line70

    public static function autoload($classname)
    {
        // 检查是否存在别名定义
        if(alias_import($classname)) return ;
        // 自动加载当前项目的Actioon类和Model类
        if(substr($classname,-5)=="Model") {
            require_cache(LIB_PATH.'Model/'.$classname.'.class.php');
        }elseif(substr($classname,-6)=="Action"){
            require_cache(LIB_PATH.'Action/'.$classname.'.class.php');
        }else {
            // 根据自动加载路径设置进行尝试搜索
            if(C('APP_AUTOLOAD_PATH')) {
                $paths  =   explode(',',C('APP_AUTOLOAD_PATH'));
                foreach ($paths as $path){
                    if(import($path.$classname))
                        // 如果加载类成功则返回
                        return ;
                }
            }
        }
        return ;
    }

 

原文地址:https://www.cnblogs.com/gaoxu387/p/2278963.html