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.

3
  • why the double slash ?? Commented Dec 15, 2018 at 8:01
  • because it's in "". so we should use double slash. Commented Dec 15, 2018 at 8:06
  • you are missing the trailing slash in the start of the namespace Commented Dec 15, 2018 at 12:06

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

I've already done it but it throws: Class 'backend\models\Book ' not found on $model = $modelName::find(); line.
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
ohhhh. thank u. it was because of space at end of Book.

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.