我正在尝试修改 1 个控制器以使用 2 个模型。这就是我在控制器中使用 loadModel 函数所做的
public function loadModel($id, $_model)
{
if (isset($_model)){
$model=$_model::model()->findByPk($id); // syntax error, unexpected "::"
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
} else {
$model=Foods::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
}
如您所见,我想为此函数创建可选参数,其中第二个参数将是模型。你能帮我做到这一点吗?
不能使用字符串作为类名来调用静态方法。只需实例化模型并调用findByPk
:
if (isset($_model)){
$model = new $_model;
$model= $model->findByPk($id);
也许会更好
/**
* @var integer $id
* @var string $_model name model class
*/
public function loadModel($id, $_model = 'Foods'){
$model = new $_model;
$model= $model->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}