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
5
  • Does this answer your question? Object Oriented PHP, Class cannot be found Commented Mar 7, 2020 at 23:03
  • When you've passed the namespace, did you include the starting backslash new \Project\Exemple\ExempleView()? Commented Mar 7, 2020 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. Commented Mar 7, 2020 at 23:19
  • 1
    @MagnusEriksson Thanks for the tip. Learned something new. Commented Mar 8, 2020 at 0:00
  • Thank you for taking the time to answer! The solution above still doesn't work (see edit 1) Commented Mar 8, 2020 at 20:43

0

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.