这是我第一次使用PHP OOP和Namespacing。我尝试动态加载该类,但始终出现错误。 Fatal error: Uncaught Error: Call to undefined function App\Controllers\DefaultController() in C:\xampp\htdocs\test\app\Core\Router.php:20
我自动加载并将命名空间(PSR-4)与Composer一起放置。在进入框架之前,我想创建自己的MVC。
test\app\Core\Router.php
<?php
namespace App\Core;
use App\Controllers\ErrorController;
class Router
{
protected $controller;
protected $action;
protected $params = [];
public function __construct()
{
$this->parseURL();
if(file_exists(APP_CTRL . $this->controller . ".php"))
{
//this is the problem.. the ErrorController() below works fine...
$class = "App\Controllers\\" . $this->controller;
$class();
}
else
{
$error = new ErrorController();
$error->error_404();
}
}
protected function parseURL()
{
$request = trim($_SERVER['REQUEST_URI'], '/');
if(!empty($request))
{
$url = explode('/', $request);
$this->controller = isset($url[0]) ? ucfirst($url[0]) . 'Controller' : 'DefaultController';
$this->action = isset($url[1]) ? $url[1] : 'index';
unset($url[0], $url[1]);
$this->params = !empty($url) ? $url : [];
}
else
{
$this->controller = 'DefaultController';
$this->action = 'index';
}
}
}
关于我的控制器。
test\app\Controllers\DefaultController.php
<?php
namespace App\Controllers;
class DefaultController extends Basecontroller
{
public function index()
{
echo 'Hi from Default';
}
}
尝试使用此Calling a class in a namespace by variable in PHP,但不起作用
已经检查了以下内容:https://coderwall.com/p/kiz5nq/instantiating-a-namespaced-php-class-dynamically和https://www.designcise.com/web/tutorial/how-to-dynamically-invoke-a-class-method-in-php
答案 0 :(得分:1)
在线...
$class = "App\Controllers\\" . $this->controller;
$class();
第二行只是尝试使用您的类名来调用函数。相反,您需要创建该类的新实例。
$controller = new $class();
然后您可以照常调用类中的任何方法...
$controller->index();