目录结构如下:
├─app
│ └─controller
│ └─StudentController.php
├─view
│ ├─resource
│ │ └─StudentView.php
│ └─Test.php
├─AutoLoad.php
└─index.php
StudentController.php:
<?php
namespace App\Controller;
class StudentController
{
}
StudentView.php:
<?php
namespace App\Controller;
class StudentController
{
}
Test.php:
<?php
namespace View;
class Test
{
}
AutoLoad.php:
<?php
class AutoLoad
{
public static function loaded($class)
{
// 获取路径
$path = dirname($class);
$class = basename($class);
// 全部小写
$path = strtolower($path);
// 拼接类名
$class = ROOT_PATH . '/' . $path . '/' . $class . ".php";
// path 转换斜杆
$class = str_replace("\\", "/", $class);
echo $class . '<br />';
include $class;
}
}
index.php:
<?php
define('ROOT_PATH', dirname(__FILE__));
require ROOT_PATH . '/AutoLoad.php';
use \App\Controller\StudentController;
use \View\Test;
use \View\Resource\StudentView;
spl_autoload_register("AutoLoad::loaded");
$test = new Test();
$db = new StudentView();
$student = new StudentController();
// 输出结果
F:/phpStudy/WWW/autoload/view/Test.php
F:/phpStudy/WWW/autoload/view/resource/StudentView.php
F:/phpStudy/WWW/autoload/app/controller/StudentController.php
有几个重要的点:
1:一个文件只实现一个功能(类/函数)
2:文件中的命名空间必须和目录结构一样,首字母大写。(最前面不要加反斜杆)
namespace App\Controller;
3:使用命名空间的时候必须使用完全限定名称(绝对路径)
use \App\Controller\StudentController;
$student = new StudentController();
spl_register_auto(“AutoLoad::loaded”);
在new
一个不存在的class
时,loaded($class)
中的参数,会包括 命名空间,这就是第二条为什么是必须的,当你用目录结构做命名空间的时候,在自动加载的时候,就可以解析成目录结构然后自动加载类文件。
github 自动加载例子