3

I want to initiate a model object using a variable model class.

        $model = new Role();
//      This works

        $className = "Role";
        $model = new $className();
//      This is not working
//      PHP Fatal Error – yii\base\ErrorException
//      Class 'Role' not found

Any help will be appreciated.

1 Answer 1

3

That means class Role (\Role) simply does not exist in root namespace.

You should use full class name with namespace, for example:

$className = 'app\models\Role';
$model = new $className();

You can get full class of any object that extended from yii\base\Object with static className() method:

use app\models\Role;

$model = new Role::className();
Sign up to request clarification or add additional context in comments.

3 Comments

That worked. Thanks. But I was wondering why I have to provide full class name with namespace even when I mentioned the namespace in the controller. $model = new Role(); works well too.
You mentioned it in namespace, for example use app\models\Role, but with this kind of initialization you simply providing string, it's not dependent of declarations in use section.
Updated the information about getting the class name. You can also upvote the answer if it was helpful.

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.