PHP Using Language构造与魔术方法相结合


PHP Using Language constructs in combination with magic methods

这个问题让我对将语言构造与PHP的神奇方法结合使用感到好奇。我创建了一个演示代码:

<?php
class Testing {
    public function scopeList() {
        echo "scopeList";
    }
    public function __call($method, $parameters) {
        if($method == "list") {
            $this->scopeList();
        }
    }
    public static function __callStatic($method, $parameters) {
        $instance = new static;
        call_user_func_array([$instance, $method], $parameters);
    }
}
//Testing::list();
$testing = new Testing();
$testing->list();

为什么Testing::list()抛出语法错误,而$testing->list()没有?

由于php保留了关键字,两者都应该失败吗?

现在PHP 7.0+支持上下文敏感的标识符,并且您的代码可以简单地工作。更新你的PHP可以解决这个问题。

这是经过批准的RFC进行了更改:https://wiki.php.net/rfc/context_sensitive_lexer.

您可以在以下(非官方)PHP7参考资料中获得更多关于新功能和突破性更改的信息:https://github.com/tpunt/PHP7-Reference#loosening-保留字限制

更新PHP 7

PHP7解决了所描述的行为,并实现了marcio提出的名为上下文敏感lexer的功能。

您的代码只需使用PHP7即可。


PHP 7之前的情况

语法错误是在PHP意识到一个方法可以通过__callStatic()使用之前抛出的,它发生在解析阶段。

您所描述的行为似乎是PHP解析器中的一个错误,至少是文档中应该描述的不一致性。

我会提交一份错误报告。抢手货


更新:OP已经提交了一份错误报告,可以在这里找到:https://bugs.php.net/bug.php?id=71157

在我看来,这是因为保留字,

如果将Testing::list();替换为call_user_func_array(['Testing', 'list'], []);,它将按预期工作。