Ari Ari - 1 month ago 5x
PHP Question

PHP Dynamic Class Loading w/ Namespaces

I'm using namespaces in PHP, and trying to load classes dynamically. My currently structure looks like this:

class Bootstrap {

protected $controller = 'home';

protected $method = 'index';

protected $params = [];

function __construct($url) {
$urlArray = $this->parseurl($url);
if(file_exists('../app/http/controllers/' . $urlArray[0] . '.php'))
$this->controller = $urlArray[0];

require_once '../app/http/controllers/' . $this->controller . '.php';

$this->controller = new Controllers\$this->controller;

public function parseurl($url) {
return $url = explode('/', filter_var(rtrim($url, '/'), FILTER_SANITIZE_URL));

The error I'm getting is:

Parse error: syntax error, unexpected '$this' (T_VARIABLE), expecting identifier (T_STRING)

How do I make it so I can load the classes with this bootstrap function?


The following line:

$this->controller = new Controllers\$this->controller;

is not valid PHP code.

If you need to instantiate classes using a dynamic class name, use an intermediate variable:

$className = 'Controllers\\' . $this->controller;
$this->controller = new $className();