根据动态变量引用模型类型时,解析运算符出错(PHP 5.2)

Background Information:

I am trying to simplify the structure of my Yii app, by moving a common function from child classes into the base class they are extending from.

I moved the loadModel($id) function from the User (child) controller into the Base controller.

Before, in UserController.php. This works:

public function loadModel($id) {
    $model = User::model()->findByPk($id);
    if ($model === null)
        throw new CHttpException(404, 'The requested page does not exist.');
    return $model;
}

After, I removed the above function, and placed it into the Controller.php, which is inherited by UserController, and many others:

public function loadModel($id) {
    $type = modelname(); // returns a string, i.e.: "User"
    $model = $type::model()->findByPk($id);
    if ($model === null)
        throw new CHttpException(404, 'The requested page does not exist.');
    return $model;
}

Problem:

I have tried this out on my local PC, running PHP 5.4.4, which works as expected, but when this is uploaded into the testing server running PHP 5.2, this throws a HTTP Error 500 (Internal Server Error). On viewing the error logs, the error was PHP Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM error, which is referring to the resolution operator on the third line.

Question:

  • Any reason why the resolution operator fails on PHP 5.2 in this case? and,
  • Are there any workarounds to making this work with the same effect?

=================

Additional Information:

The global modelname function I am using, which returns the model name, i.e.: "User":

function modelname() {
    return Yii::app()->controller->id;
}
查看全部
dtqf81594
dtqf81594
2013/03/08 10:13
  • yii
  • php
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

2个回复