php - PHP 5.4 自动加载器无法按预期使用命名空间
问题描述
我的项目根目录中有一个 autoloader.php:
<?php
spl_autoload_register('AutoLoader');
function AutoLoader($className)
{
// imports files based on the namespace as folder and class as filename.
$file = str_replace('\\',DIRECTORY_SEPARATOR, $className);
require_once $file . '.php';
}
在我的 webroot 文件夹中,我有一个 index.php 文件,我需要这个自动加载器:
require_once '../autoload.php';
现在在我的项目的根目录中,我有一个控制器文件夹和一个 adminContoller.php 文件,如下所示:
<?php
namespace controllers;
class adminController extends Controller
{
现在我收到这些错误:
警告:require_once(adminController.php):打开流失败:第 9 行的 /some folder/autoload.php 中没有这样的文件或目录
致命错误:require_once():无法在第 9 行的 /some folder/autoload.php 中打开所需的 'adminController.php' (include_path='.:/usr/share/pear:/usr/share/php')
这是 autoload.php 中的第 9 行require_once $file . '.php';
我的结构:
编辑 1 个完整的 index.php
<?php
require_once '../autoload.php';
define('WEBROOT', str_replace("webroot/index.php", "", $_SERVER["SCRIPT_NAME"]));
define('ROOT', str_replace("webroot/index.php", "", $_SERVER["SCRIPT_FILENAME"]));
//require(ROOT . 'config/core.php');
require(ROOT . 'router.php');
require(ROOT . 'request.php');
require(ROOT . 'dispatcher.php');
$dispatch = new Dispatcher();
$dispatch->dispatch();
编辑 2 完整的 dispatcher.php 文件:
<?php
class Dispatcher
{
private $request;
public function dispatch()
{
$this->request = new Request();
Router::parse($this->request->url, $this->request);
$controller = $this->loadController();
call_user_func_array([$controller, $this->request->action], $this->request->params);
}
public function loadController()
{
$name = $this->request->controller . "Controller";
$file = ROOT . 'Controllers/' . $name . '.php';
require($file);
$controller = new $name();
return $controller;
}
}
解决方案
推荐阅读
- ios - Xcode 无法为预构建框架生成代码覆盖率
- java - Google 测试框架是否支持 JAVA 语言。?还是只支持 C++?如果是,Google test Framework for JAVA 的替代方案是什么
- reactjs - 通过fetch发布数据后如何清除输入并使代码执行成功
- python - 我如何找到这个特定字符串的多次出现并将它们拆分成一个列表?
- opencv - 如何通过知道像素和相机与物体之间的距离来计算图像的尺寸?
- java - 正则表达式显示不同的同时返回不同的结果
- windows - 使用批处理脚本将特定列和行值复制到新列
- haskell - 嵌套循环格式
- vb.net - 如何使用 AT 命令发送长消息,vb.Net
- c++ - 为什么我在函数内部使用引用并通过引用返回它仍然有效?