1

I need to create a model by string name that it is a variable.

       function($modelName){ 
               $modelName= "backend\\models\\".$modelName;

               $modelClass = Yii::createObject([
                          'class' => $modelName,
                    ]); 
                    $model =  $modelClass::find(); 
            }

when I pass Book(it is extracted form DB) as modelName to function, it throws an error: Class backend\models\Book does not exist. but when I write $modelName= "backend\\models\\Book"; it works fine.

I know it is because of run time and compile time. but I don't know how to solve it. because $modelName is Characterized at run time.

Rahman
  • 410
  • 6
  • 26

1 Answers1

2

You are accessing to a static method using an object. You should access to the static method just using the class name eg:

$modelName = 'backend\models\\' . $modelName;
$model = $modelName::find(); 

And remember that $modelName::find() don't return a model but just the query object for a model. To obtain a model you should use eg: $modelName::find()->where(['id'=>$your_value])->one();

rob006
  • 21,383
  • 5
  • 53
  • 74
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
  • I've already done it but it throws: `Class 'backend\models\Book ' not found` on `$model = $modelName::find(); ` line. – Rahman Dec 15 '18 at 08:34
  • are you sure the model is in backend and not in common ???' and have you tried adding the slash at the begin of the string? .... also looking to your comment .. check if the Book name don't contain a blank at the end i mean 'Book ' instead of 'Book' .. try trim off the blank when you select form db – ScaisEdge Dec 15 '18 at 10:34
  • ohhhh. thank u. it was because of space at end of Book. – Rahman Dec 15 '18 at 12:13