【问题标题】:Class property as class name类属性作为类名
【发布时间】:2012-10-11 19:43:49
【问题描述】:
$this->property = 'SomeClass';

$x = new $this->property();     // works
$x = $this->property::create(); // fails (parse error)

这是 PHP 中的错误吗?

可以使用属性调用静态方法,而不将值分配给新变量,而是使用该变量吗?

【问题讨论】:

  • 你使用的是什么版本的 PHP?
  • php 5.3.0.对别人有用吗?
  • 我不知道。此行为在范围解析运算符文档的 cmets 中,但由于某种原因,该运算符不在运算符文档的优先图表中。据我所知,您不能将 :: 与任何东西链接,包括它自己。在 5.3 中使用变量来引用类名 :: 的能力是新的,但我想他们并没有比这更进一步。
  • @Alex,你为什么不使用$x->create(),因为你有一个SomeClass的实例,无论如何,你不能这样做AFAIK。

标签: php class properties static


【解决方案1】:

使用call_user_func

$x = call_user_func(array($this->property, 'create'));

【讨论】:

    【解决方案2】:

    它已经作为一个 bug 输入了几个月,仍然处于 Open 状态,所以我会选择 yes。

    https://bugs.php.net/bug.php?id=61397

    同样,

    https://bugs.php.net/bug.php?id=54095

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-21
      • 1970-01-01
      • 2016-05-13
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      • 2013-07-05
      • 2011-04-25
      相关资源
      最近更新 更多