1

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];
            unset($urlArray[0]);
        }

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

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

        var_dump($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?

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

Comments

0

This should work:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.