Eduardo Eduardo - 4 months ago 21
PHP Question

Yii 2. Using a model from a string

I have a weird scenario, I am getting the model name as a string, so If I wanted to use it, but how do I manage the import class part? Any ideas?

I have tried:

$model = new $tmpModel;
var_dump($model);


Now I get: "Class 'Organization' not found", but I have imported the class manually just to test, but still error.

use app\models\Organization;


Any ideas?

EDIT: I think I needed some sleep. With help of comments here code looks like these:

$className = "app\\models\\".$this->modelSave;

$model = Yii::createObject([
'class' => $className,
]);

var_dump($model);

Answer

In YII way you can Use as ..

$className = 'path\folder\FileName';
$model = Yii::createObject([
          'class' => $className,
         ]);

This method can also identify dependent objects, instantiate them and inject them into the newly created object.