【问题标题】:Why does invoking callable properties in PHP 7 work?为什么在 PHP 7 中调用可调用属性有效?
【发布时间】:2017-10-07 22:16:11
【问题描述】:

考虑以下代码:

interface Doll
{
    /**
     * @return string
     */
    function __invoke();
}

class LargeDoll
{
    private $inner;

    function __construct(Doll $inner)
    {
        $this->inner = $inner;
    }

    function __invoke()
    {
        return $this->inner() . ' world';
    }
}

这不起作用,因为它期望 $this->inner 是一个方法,而不是一个可调用的属性。

然后我想到,就像拥有(new LargeDoll)(); 一样,如果该属性也被包裹在括号中呢?于是我在 3v4l 上进行了测试:

return ($this->inner)() . ' world';

And found that it works for PHP 7, but not for previous versions.

但是,我找不到任何提及此in the changelogs

我在哪里可以找到有关此功能的更多信息?

【问题讨论】:

    标签: php php-7


    【解决方案1】:

    使用 IIFE(实际上是 ($this->inner)())的功能是 Nikita Popov 在 PHP7 中实现的 Uniform Variable Syntax RFC 的一部分。

    这是解析器中更好的变量语法处理的结果。考虑到 PHP7 的目标之一是彻底检查语法解析,我认为他们已经取得了一些真正的进展。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-05
      • 2019-01-16
      相关资源
      最近更新 更多