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:
=================
Additional Information:
The global modelname function I am using, which returns the model name, i.e.: "User":
function modelname() {
return Yii::app()->controller->id;
}
I have found the answer here:
http://php.net/manual/en/language.oop5.paamayim-nekudotayim.php
The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.
When referencing these items from outside the class definition, use the name of the class.
As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).
Basically, I had to upgrade the PHP version to be able to reference a class dynamically.
Actually, you don't have to upgrade to reference the class dynamically. Yii does it without and yii supports PHP 5.2. If you are interested, I can see if I can dig up how it is done, but I've run into the same problem and resolved it on PHP 5.2
Edit: Ok, here's the info. I posted the original info on a Yii wiki page.
Here's the code that returns a Yii singleton model:
$thisModel = call_user_func($modelname, 'model');
But, per DCoder, it looks like CActiveRecord::model($modelname)
will also work:
Yii info here: http://www.yiiframework.com/doc/api/1.1/CActiveRecord#model-detail