Alex Jose
Alex Jose

Reputation: 464

Unable to initiate model object using variable classname in Yii2

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.

Upvotes: 3

Views: 2458

Answers (1)

arogachev
arogachev

Reputation: 33548

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();

Upvotes: 3

Related Questions