-1

虽然我知道可以通过多种方法调用静态方法,例如:

A::staticFunction();

或者

$class = 'A';
$class::staticFunction();

或者

$a = new A(); // Assume class has been defined elsewhere
$a->staticFunction();

但是,有人可以解释为什么以下方法不起作用,如果可能的话,如何使这项工作(不求助于提供的解决方案):

// Assume object $b has been defined & instantiated elsewhere
$b->funcName::staticFunction(); // Where funcName contains the string 'A'

这会产生以下 PHP 解析错误:

解析错误:语法错误,意外的 '::' (T_PAAMAYIM_NEKUDOTAYIM)

典型的工作解决方案(遵循第二种方法)(如果可能,最好避免):

// Assume object $b has been defined & instantiated elsewhere
$funcName = $b->funcName; // Where funcName contains the string 'A'
$funcName::staticFunction();
4

1 回答 1

0

::运算符用于引用非实例化类。这意味着您正在引用static方法或变量,或者const. 方法的标志static是它们不能与您的实例一起使用。它们本质上是独立的函数,不能$this用来引用你的类的实例。

因此,您不能通过引用实例来引用静态方法。你需要使用

self::function();

或者

$this->function();

虽然后者使它看起来可能是实例的一部分,但它只是为了完整性而包含在内。

于 2014-05-26T14:18:05.440 回答