我有一个 string
变量,其中包含 model 的类名,我想使用该变量在所述 model 上调用一个方法,是这可能吗??
我的代码:
foreach($tables as $tables)
{
$table = ArrayHelper::getValue($tables, 'table_name');
$model = \common\models\$table::findAll();
var_dump($model);
}
更简单的版本:
$table = "DataAnalysis";
$model = \common\models\$table::findAll();
var_dump($model);
当我运行该代码时,出现以下错误:
<块引用>带有消息“语法错误,意外的“$table”(T_VARIABLE),需要标识符(T_STRING)”的异常“ParseError”
给定变量中包含的字符串,我可以做些什么来调用 model 吗?
答案 0 :(得分:2)
你应该这样做,
$model="\\common\\models\\DataAnalysis";
$model::findAll();
或
$table="DataAnalysis";
$model="\\common\\models\\{$table}";
$model::findAll();
而不是call_user_func()
对于一个简单的任务来说代码太多
编辑
如果你需要实例化类而不是静态调用,你可以简单地做
$table="DataAnalysis";
$model="\\common\\models\\{$table}";
new $model();
答案 1 :(得分:1)
call_user_func()
来完成。// If you have the name of the ActiveRecord class, like in you comment
$class = 'DataAnalysis';
/** @var ActiveQuery $query */
$query = call_user_func($class . '::find');
// Then use the query as you want
foreach($query->each() as $model) {
// Do something with your model
}
如果您不确定变量中的值是否始终正确,请将其包裹在 try/catch
中。
如果您拥有的是表名而不是类名,您可以尝试使用 Yii inflector camelize method 进行转换。
use yii\helpers\Inflector;
$tableName = 'some_snake_case_name';
$className = Inflector::camelize($tableName);
/** @var ActiveQuery $query */
$query = call_user_func($className . '::find');
// If you want to filter results
$query->where(...);
// Then use the query as you want
foreach($query->each() as $model) {
// Do something with your model
}
call_user_function
docs are here。