1.使用spl_autoload_register函数注册一个自己定义的自动加载函数
2.当在代码中new一个不存在的类的时候,上面的函数会被调用,不存在的类名会被作为参数传入该函数中
3.兼容了两种方式,命名空间对应目录的方式 \app\test,类名下划线分割对应目录的方式app_test,都是对应的app目录下的test.php文件,类名要和文件名一致
4.set_include_path(),可以有多个用冒号:隔开,动态设置php.ini中的include_path 配置选项

<?php
class Application {
private static $instance = null;
private $libPath = './';
private $phpExt = '.php';
public function setLibPath($path, $autoload = false) {
$this->libPath = trim(trim($path), DIRECTORY_SEPARATOR);
set_include_path($this->getLibPath());
if ($autoload) {
spl_autoload_register(array('Application', 'load'));
}
return $this;
}
public static function instance() {
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
//获取文件后缀
public function getPhpExt() {
return $this->phpExt;
}
//设置文件后缀
public function setPhpExt($ext) {
$this->phpExt = $ext;
return $this;
}
//设置根路径
public function setPath($path) {
$this->path = rtrim(trim($path), DIRECTORY_SEPARATOR);
return $this;
}
//设置自动加载的路径
public function getLibPath() {
return $this->path . DIRECTORY_SEPARATOR . $this->libPath;
}
//自动加载函数
public static function load($class) {
$pos = strrpos($class, '\\');
if ($pos !== false) {
$ns = str_replace('\\', DIRECTORY_SEPARATOR, substr($class, 0, $pos + 1));
$className = substr($class, $pos + 1);
} else {
$ns = DIRECTORY_SEPARATOR;
$className = $class;
}
if (strpos($className, '_') !== false) {
$className = str_replace('_', DIRECTORY_SEPARATOR, $className);
}
$ins = self::instance();
$classFile = $ins->getLibPath() . $ns . $className . $ins->getPhpExt();
if (!(include $classFile)) {
throw new Exception('load class failed: class=' . $class . ' file=' . $classFile);
}
}
}
Application::instance()->setPath(dirname(__FILE__))->setLibPath(DIRECTORY_SEPARATOR, true);
//测试,在根目录创建app目录,下面创建这两个文件
new app_user();
new \app\admin();

app目录下面的user.php

<?php
class app_user{
public function __construct(){
new \app\admin();
}
}

app目录下的admin.php

<?php
namespace app;
class admin{}

最新文章

  1. WPF中嵌入普通Win32程序的方法
  2. Web开发中的主要概念
  3. python中list注意事项
  4. 怎样把网站js文件合并成一个?几种方法可以实现
  5. Spark系列(三)SparkContext分析
  6. Oracle中用一张表的字段更新另一张表的字段
  7. idea配置tomcat.md
  8. EBS 信用检查(一)
  9. HTML标签 按功能排序
  10. mybatis_11关联查询_多对多
  11. Java编程的逻辑 (92) - 函数式数据处理 (上)
  12. Django 知识总结(一)
  13. centos7挂载本地yum文件
  14. 用venv 配置不同的开发环境
  15. Android 如何修改默认输入法
  16. 【BZOJ2217】[Poi2011]Lollipop 乱搞
  17. Python初学者第十六天 文件处理操作练习
  18. Kali-linux渗透攻击应用
  19. Linux系统之路——如何在CentOS7.2安装R和RStudio(Server)
  20. jvm垃圾回收策略

热门文章

  1. aspx使用KindEditor副文本框插件出现检测到有潜在危险
  2. luoguP3979 遥远的国度
  3. github配置ssh及多ssh key问题处理
  4. 4. gitlab 安装、项目创建
  5. vlmcsd
  6. django中对数据库生成记录操作失败
  7. Python学习笔记2基本语法规则_20170611
  8. ionic4打包和ngix配置
  9. Python网络编程基础 ❶ 计算机网络基础 初用socket模块
  10. lincense更新失败