首页 > 解决方案 > 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;
    }
}

标签: phpnamespacesautoload

解决方案


推荐阅读