2
我尝试重构我的代码并使用自动加载系统。现在,我在做:自动加载名称空间的类文件
的index.php:
namespace example_com;
use example_com\Core\Application;
require 'Application.php';
$app = new Application();
$app->MyCustomFunction();
我想消除需要线;每当我调用新的Application()或新的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();
Application.php
namespace example_com\Core;
class Application
{
//..contruct, properties, functions
}
= DEBUG OUTOUT =
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"
我打算使用这在s中的不同文件中AME项目
更新1: 文件夹结构
App/
--Controllers/
----XController.php
----YController.php
Core/
--Controllers/
----IBaseController.php
----BaseController.php
--Application.php
index.php
所有的课程都在同一个基础文件夹中吗?我想你应该把所有的类都放在同一个文件夹中,这样你就可以创建一个'spl_autoload_register()',它将加载到页面顶部(可能在一个包含的配置类型文件中),并覆盖所有的类你的应用?我不认为我会按每班制作自动加载器。这可能会减慢你的应用程序。 – Rasclatt
我所有的课程都不在同一个文件夹中。我编辑显示我的文件夹结构的主题 – reladawrefurhost