简体   繁体   English

php 通过变量 class 名称访问 static 成员

[英]php access static member by variable class name

Now I am working with yii framework and I'd like to wrote something like this:现在我正在使用 yii 框架,我想写这样的东西:

protected static $model = "Customer";
...
public function actionIndex() {
    $model::model()->find(...

Now it works:现在它起作用了:

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(...

but creating object for access static member is a bad thing.但是创建 object 来访问 static 成员是一件坏事。 how to avoid it?如何避免?

getClass takes object as first parameter and it is not suitable for this purpose getClass 以 object 作为第一个参数,不适用于此目的

google say:谷歌说:

$a = constant($myClassName . "::CONSTANT");
$b = call_user_func(array($myClassName, "static_method"));

it looks like a horrible peace of shit.它看起来像一个可怕的狗屎和平。 using this may make many troubles.使用它可能会带来很多麻烦。 another solution?另一种解决方案?

oh: my problem was another:哦:我的问题是另一个:

$controller::$NAME::model() // error

$controller_name = $controller::$NAME
$controller_name::model() // good

thanks谢谢

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"));

Is the primary way to do it.是主要的方法。 I'm not quite sure why this would cause any problems.我不太确定为什么这会导致任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM