用变量类名访问PHP静态成员

3

我现在正在使用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

谢谢

2个回答

6
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

1
如果这个回答解决了你的问题,请记得将其标记为答案,并在新问题中发布其他问题(以便它也可以帮助其他用户)。 - Lepidosteus

0
call_user_func(array($myClassName, "static_method"));

这是主要的方法。我不太确定为什么这会引起任何问题。


1
比较 call_user_func(array("Customer", "read", $id)); 和 Customer::read($id) = - puchu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接