문제

I am trying to modify 1 controller to work with 2 models. This is what I have done with loadModel function in my controller

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;
    }
}

As you can see I want to create optional parameter for this function where second parameter will be the Model. Can you help me to achieve this?

도움이 되었습니까?

해결책

You can't use string as class name to call static method. Just instantiate model and call findByPk:

if (isset($_model)){
    $model = new $_model;
    $model= $model->findByPk($id);

다른 팁

Perhaps it would be better

/**
* @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;
        }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top