您的位置:首页 > 编程语言 > PHP开发

spl_autoload_register()自动加载+命名空间的使用

2017-11-03 20:03 821 查看
我们首先在AutoLoading文件夹下创建了一个loading类,举例来看:AutoLoading\loading:
<?php

namespace AutoLoading;

class loading
{
public static function  autoload($className)
{
//把 \ 转换成(目录风格符)DIRECTORY_SEPARATOR
//便于兼容在Linux系统下文件找,在Windows系统下(/ \ 是通用的);
//由于namespace 很规格,所以很快就能直接找到
$fileName = str_replace('\\',DIRECTORY_SEPARATOR, DIR .'\\'.$className).'.php';//替换符号
echo $fileName;
if (is_file($fileName)){//判断文件是否存在
include ($fileName);
} else {
echo $fileName.'is not exist';
}
}
}
上面就是自动加载的引入类文件的方法,下面使用spl_autoload_register()这个函数来注册:
index.php
//把当前目录定义为绝对路径
define('DIR',dirname(__FILE__));
//加载类文件
require DIR . '/loading.class.php';
//必须是static方法调用,不能使用use
spl_autoload_register("\\AutoLoading\\loading::autoload");
Lib\Db::demo();//引入Lib目录下的Db类
这样便可以很轻松的将不同文件夹的的类引如进来。

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  php