我想动态创建一些类的实例,但是我得到一个错误,说找不到类(如果它是从字符串动态调用的),否则如果我通常输入类名来创建类的实例“不使用字符串”将成功创建。
错误:
致命错误:第31行的C:\ wamp \ www \ framework \ controllers \ RouterController.php中找不到类'SiteController'
芯/ Controller.php这样
namespace core;
class Controller{
function __construct(){
$files = glob('./' . '/*.php');
foreach ($files as $file) {
require_once($file);
}
}
}
控制器/ RouterController.php
namespace controllers;
require_once("core/Controller.php");
use \core\Controller;
use \controllers\SiteController;
class RouterController extends Controller{
private $url;
private $controller;
private $controllerName;
private $action;
function __construct($url){
parent::__construct();
$this->url = $url;
$this->splitUrl();
// the following is working successfully
$this->controller = new SiteController();
$this->controller->{"$this->action"}();
if($this->controllerName != '' && $this->action != ''){
// but this is not working
$this->controller = new $this->controllerName();
$this->controller->{"$this->action"}();
}
}
private function splitUrl(){
$url = preg_split("#/#", $this->url);
$this->controllerName = !empty($url[0]) ? ucfirst($url[0])."Controller" : null;
$this->action = !empty($url[1]) ? $url[1] : "index";
}
}
控制器/ SiteController.php
namespace controllers;
class SiteController{
public function index(){
echo "this is index";
}
}