Answer the question
In order to leave comments, you need to log in
Dynamic creation of class object when using namespace?
Good afternoon!
The router has a method:
public function Run()
{
$uri = $this -> getURI();
foreach ($this -> routes as $uriPattern => $path) {
if (preg_match("~$uriPattern~", $uri))
{
$rout = explode('/', $path);
// print_r($rout);
$controllerName = array_shift($rout) . 'Controller';
$actionName = array_shift($rout);
$controllerFile = ROOT . "/controllers/{$controllerName}.php";
if (file_exists($controllerFile)) {
include_once($controllerFile);
}
$controllerObject = new Controllers\installAppController;
/*
* нужно вот так как то:
* $controllerObject = new Controllers\$controllerName;
*/
$result = $controllerObject -> $actionName();
if ($result !== null) {
break;
}
}
}
}
use Calculation\Margin\Controllers;
<?php
namespace Calculation\Margin\Components\Router;
require_once ROOT.'/config/routes.php';
use Calculation\Margin\Config\RoutesList;
use Calculation\Margin\Controllers;
class Router
{
private $routes;
public function __construct ()
{
$this -> routes = RoutesList::getRoutes();
}
private function getURI(): string
{
if (!empty($_SERVER['REQUEST_URI'])) {
return trim($_SERVER['REQUEST_URI'], '/');
}
}
public function Run()
{
$uri = $this -> getURI();
foreach ($this -> routes as $uriPattern => $path) {
if (preg_match("~$uriPattern~", $uri))
{
$rout = explode('/', $path);
// print_r($rout);
$controllerName = array_shift($rout) . 'Controller';
$actionName = array_shift($rout);
$controllerFile = ROOT . "/controllers/{$controllerName}.php";
if (file_exists($controllerFile)) {
include_once($controllerFile);
}
$controllerObject = new Controllers\installAppController;
/*
* нужно вот так как то:
* $controllerObject = new Controllers\$controllerName;
*/
$result = $controllerObject -> $actionName();
if ($result !== null) {
break;
}
}
}
}
}
Answer the question
In order to leave comments, you need to log in
$className = '\\Calculation\\Margin\\Controllers\\'.$controllerName;
$controllerObject = new $className;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question