【问题标题】:How do I call a static method of a class stored as a variable?如何调用存储为变量的类的静态方法?
【发布时间】:2013-02-13 22:47:06
【问题描述】:

为什么在类实例上下文中,$this->className::staticMethod 形式的调用不起作用,而 $className::staticMethod 形式的调用却起作用?

在下面的示例中,callDoSomething2 有效,但 callDoSomething 无效(我收到解析器错误)。我正在使用 PHP 版本 5.3.15。

<?php
class A {
    private $className;

    public function __construct($className) {
        $this->className = $className;
    }

    public function callDoSomething() {
        $this->className::doSomething();
    }

    public function callDoSomething2() {
        $className = $this->className;
        $className::doSomething();
    }
}

class B {
    public static function doSomething() {
        echo "hello\n";
    }
}

$a = new A('B');
$a->doSomething();

【问题讨论】:

标签: php


【解决方案1】:

callDoSomething2 是一种方法,另一种方法是使用类似于

call_user_func("{$this->className}::doSomething");

【讨论】:

  • 您能否解释一下为什么callDoSomething 不起作用? PHP 解析器无法处理?
  • 是的,这是一个解析错误 -- PHP 解析器无法处理。
猜你喜欢
  • 2010-10-13
  • 2012-10-13
  • 2017-04-16
  • 1970-01-01
  • 1970-01-01
  • 2021-06-08
  • 2010-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多