skip to Main Content

Does this usage make sense? Will it cause any problems later?

function model($folder, $file)
{
    global $db;
    if (is_file(path . 'app/models/' . $folder . '/' . $file . '.php')) {
        require_once(path . 'app/models/' . $folder . '/' . $file . '.php');
        return new $file($db);
    }
}

echo model('admin', 'common')->get();

2

Answers


  1. Chosen as BEST ANSWER

    Revise

    function model($folder, $file)
    {
        global $db;
        if (is_file(path . 'app/models/' . $folder . '/' . $file . '.php')) {
            require_once(path . 'app/models/' . $folder . '/' . $file . '.php');
            if (class_exists($file)) {
                return new $file($db);
            } else {
                throw new Exception("Class not found.");
            }
        } else {
            throw new Exception("Model not found.");
            
        }
    }
    
    try {
        echo model('admin', 'common')->get();
    } catch (Exception $error) {
        echo $error;
    }
    

    I don't want to use autoload. Thanks.


  2. That works fine since it’s possible to instantiate class by a variable containing that class name.

    But I suggest, if you can, to use composer to auto-load classes. You can find tutorial about that.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search