dou91855 2018-10-24 11:09
浏览 109

PHP 5.4自动加载器与命名空间无法正常工作

I have an autoloader.php in the root of my project:

<?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';
}

in my webroot folder I have an index.php file where I require this autoloader:

require_once '../autoload.php';

now in the root of my project I have a controllers folder and an adminContoller.php file that looks like this:

<?php

namespace controllers;

class adminController extends Controller
{

now I get these errors:

Warning: require_once(adminController.php): failed to open stream: No such file or directory in /some folders/autoload.php on line 9

Fatal error: require_once(): Failed opening required 'adminController.php' (include_path='.:/usr/share/pear:/usr/share/php') in /some folders/autoload.php on line 9

this is line 9 in autoload.php require_once $file . '.php';

my structure:

enter image description here

EDIT 1 full 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();

EDIT 2 full dispatcher.php file:

<?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;
    }
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 易康econgnition精度验证
    • ¥15 线程问题判断多次进入
    • ¥15 msix packaging tool打包问题
    • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
    • ¥15 python的qt5界面
    • ¥15 无线电能传输系统MATLAB仿真问题
    • ¥50 如何用脚本实现输入法的热键设置
    • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
    • ¥30 深度学习,前后端连接
    • ¥15 孟德尔随机化结果不一致