现在我正在使用yii框架,我想写这样的东西:
protected static $model = "Customer";
...
public function actionIndex() {
$model::model()->find(...
现在它工作了:
protected static $model = "Customer";
protected static $model_obj;
...
public function __construct($controller, $id) {
$this->model_obj = new self::$model;
...
public function actionIndex() {
$model_obj::model()->find(...
但是为访问静态成员创建对象是一件坏事。如何避免?
getClass将对象作为第一个参数,它不适合用于此目的
谷歌称:
$a = constant($myClassName . "::CONSTANT");
$b = call_user_func(array($myClassName, "static_method"));
这看起来像是一种可怕的平静。使用这个可能会带来很多麻烦。另一种解决方案?
哦!我的问题是另一个:
$controller::$NAME::model() // error
$controller_name = $controller::$NAME
$controller_name::model() // good
感谢
class foo
{
public static function bar()
{
return 42;
}
}
// class name as string
$class = 'foo';
var_dump($class::bar()); // 42
// method name as string
$method = 'bar';
var_dump(foo::$method()); // 42
// class AND method names as strings
var_dump($class::$method()); // 42
call_user_func(array($myClassName, "static_method"));
是做这件事的主要方法。我不太清楚为什么这会引起任何问题。