Reputation: 452
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.
Upvotes: 1
Views: 1135
Reputation: 133380
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();
Upvotes: 2