1

I'm currently trying to do create a class from a string with its namespace already present.

namespace Project\Manager;

use Project\Exemple\ExempleView;

class Manager{
    private $db;
    function __construct($db){
        $this->db = $db;
    }

    public function displayView($module = null, $action = null){
        if($module != null){
            $sql = '
                SELECT *
                FROM urls
                WHERE urls_module = "'.$module.'"
                '.($action != null ? 'AND urls_action = "'.$action.'"' : '').'
                ORDER BY urls_id DESC 
                LIMIT 1
            ';

            $url = $this->db->read($sql);

            if(!isset($url['error'])){
                $class = $url['urls_class'];
// Edit 1
require_once $class.'.php';
                $action = $url['urls_action'];
                $view = new $class();

                $view->$action();
            }
        }
    }
}

With this, I get the following error :

Fatal error: Uncaught Error: Class 'ExempleView' not found in C:\wamp64\www\project\src\core\manager\manager.class.php on line 27

I've tried to pass the namespace into my variable(Project\Exemple\ExempleView) but it still didn't work. My class is correctly loaded in my project and if I try to call it directly (new ExempleView()) it works. Is there a way to create my class using a string this way?

--Edit 1 I've tried adding a require_once of my class but it still doesn't work

Warning: require_once(ExempleView.php): failed to open stream: No such file or directory in C:\wamp64\www\project\src\core\manager\manager.class.php on line 27
Karnaham
  • 11
  • 3
  • Does this answer your question? [Object Oriented PHP, Class cannot be found](https://stackoverflow.com/questions/60444168/object-oriented-php-class-cannot-be-found) – toh19 Mar 07 '20 at 23:03
  • When you've passed the namespace, did you include the starting backslash `new \Project\Exemple\ExempleView()`? – El_Vanja Mar 07 '20 at 23:18
  • 1
    @El_Vanja - You don't need that when you have the class name in a string like this. It will work either way. – M. Eriksson Mar 07 '20 at 23:19
  • 1
    @MagnusEriksson Thanks for the tip. Learned something new. – El_Vanja Mar 08 '20 at 00:00
  • Thank you for taking the time to answer! The solution above still doesn't work (see edit 1) – Karnaham Mar 08 '20 at 20:43

0 Answers0