找不到动态类参考PHP

时间:2015-03-17 14:27:09

标签: php

我的routing.php(自动提前文件)

<?php
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"])) {
    return false;
} else {
    include 'index.php';
}

我的index.php

<?php

namespace MVC;
require_once "controllers/AdminController.php";
use MVC\controllers\AdminController as AdminController;

/*
 * Break the requested URI down into an array
 */

$request = trim($_SERVER["REQUEST_URI"]);
$request = explode("/", $request);
$request = array_filter($request);

$additional = array();
$singles = array();

/*
 * Get the method/controller from the requested URL
 */

foreach($request as $key=>$item) {
    switch($key) {
        case 1:
            $controller = $item;
            break;
        case 2:
            $method = $item;
            break;
        default:
            if($key > 2) {
                $item = explode("=", $item);
                if(isset($item[1])) {
                    //key item pair, data
                    $pairs[$item[0]] = $item[1];

                    /*
                     * Make the assumption that any value passed in
                     * as an assigned value is data and not a route
                     *
                     * Append this to the pairs array as its own key/item
                     */
                } else if(isset($item[0])) {
                    echo "<b>WARNING: \"" . $item[0] . "\" has no key/value!</b>";
                }
            }
            break;
    }
}

/*
 * Handle the fact that these might not have been requested
 */


if(!isset($controller))
    $controller = 'index';

$controller = ucfirst($controller) . "Controller";

if(!isset($method))
    $method = 'index';

$controller = new $controller();

我的AdminController.php(在controllers / AdminController.php中找到)

<?php

namespace MVC\controllers;

require_once "libs/Controller.php";
use MVC\libs\Controller;

class AdminController extends Controller {

}

最后我的控制器超类在libs / Controller.php中找到

<?php

namespace MVC\libs;

class Controller {

}

我的问题是这一行

$controller = new $controller();

我知道这是一个变量 - 这是我的意图,我试图根据URI请求动态加载这个类。

给出了这个错误:

127.0.0.1:50342 [500]: /admin/users/id=555/action=ban - Class 'AdminController' not found in /home/jack/PhpstormProjects/mvc/index.php on line 64

我已经检查了它是否需要课程,使用它作为&#34; AdminController&#34;但它仍然无法在相关的命名空间中找到对它的引用 - 我和#39;我认为因为它的动态可能会有一些问题吗?

干杯!

编辑:我的文件夹结构

controllers
   AdminController.php
libs
   Controller.php
index.php
routing.php

1 个答案:

答案 0 :(得分:2)

这是命名空间问题。您不能像以前一样同时使用变量类名称 use语句。您的变量在运行时获取其值,而use导入在编译时完成(use无法在块作用域中使用,原因相同)。参见:

use foo as bar;

class foo {
   public function __construct() {
      echo "OK\n";
   }
}

new foo(); // OK
new bar(); // OK

$foo = 'foo';
$bar = 'bar';

new $foo(); // OK
new $bar(); // Fatal error: Class 'bar' not found

解决方案:在变量中使用完整的类名(带绝对命名空间)。