【发布时间】:2017-11-03 20:45:30
【问题描述】:
我尝试重构我的代码并使用自动加载系统。目前,我正在做:
index.php:
namespace example_com;
use example_com\Core\Application;
require 'Application.php';
$app = new Application();
$app->MyCustomFunction();
我想去掉 require 行;每当我调用 new Application() 或 new Class() 时,我都想要求;
我尝试如下:
index.php
namespace example_com;
use example_com\Core\Application;
spl_autoload_register(function($className) {
$namespace = str_replace("\\", "/", __NAMESPACE__);
$className = str_replace("\\", "/", $className);
$class = ROOT . (empty($namespace) ? "" : $namespace . "/") . "{$className}.php";
include_once($class);
});
//require 'Application.php';//remove this
$app = new Application();
$app->MyCustomFunction();
应用程序.php
namespace example_com\Core;
class Application
{
//..contruct, properties, functions
}
=调试输出=
spl_autoload_register(function($className) { //$className: "example_com/Core/Application"
$namespace = str_replace("\\", "/", __NAMESPACE__); //$namespace: "example_com"
$className = str_replace("\\", "/", $className);
$class = ROOT . (empty($namespace) ? "" : $namespace . "/") . "{$className}.php"; //$className: "example_com/Core/Application" $namespace: "example_com" $class: "example_com/example_com/Core/Application.php"
我打算在同一个项目的不同文件中使用它
更新 1: 文件夹结构
App/
--Controllers/
----XController.php
----YController.php
Core/
--Controllers/
----IBaseController.php
----BaseController.php
--Application.php
index.php
【问题讨论】:
-
您的所有课程都在同一个基本文件夹中吗?我认为您应该将所有类都放在同一个文件夹中,这样您就可以创建一个
spl_autoload_register(),它将加载到页面顶部(可能在包含的配置类型文件中)并在整个应用程序中覆盖您的所有类?我不认为我会在每个班级的基础上制作一个自动加载器。这可能会降低您的应用速度。 -
我所有的课程都不在同一个文件夹中。我编辑显示我的文件夹结构的主题
标签: php class spl-autoload-register