【问题标题】:How to call an invokable property of a class [duplicate]如何调用类的可调用属性[重复]
【发布时间】:2020-08-04 17:57:16
【问题描述】:

我不明白为什么类属性是一个可调用对象this->property()

<?php

class A
{
    public function __invoke($t)
    {
        return $t * 3;
    }
}


class B
{
    public function __construct(A $a)
    {
        $this->a = $a;
    }

    public function yo($t)
    {
        return $this->a($t);
    }
}

echo (new B(new A))->yo(8);

这将导致错误:

<br />
<b>Fatal error</b>:  Uncaught Error: Call to undefined method B::a() in [...][...]:21
Stack trace:
#0 [...][...](28): B-&gt;yo(8)
#1 {main}
  thrown in <b>[...][...]</b> on line <b>21</b><br />

为了完成这项工作,我必须将方法 yo 更改如下:

public function yo($t)
{
    return ($this->a)($t); // this works
    $x = $this->a; // this works
    return $x($t); // as well
}

我在网上找不到任何解释。有什么想法吗?

【问题讨论】:

    标签: php


    【解决方案1】:

    $this-&gt;a($t) 不明确。这可能意味着使用参数$t 调用$thisa 方法,或者获取$thisa 属性并(如果它是可调用的)使用参数$t 调用它。

    由于方法调用比包含可调用对象的属性更常见,因此默认为前一种解释。您需要括号来覆盖该解析。

    【讨论】:

      猜你喜欢
      • 2018-04-12
      • 1970-01-01
      • 2014-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-06
      相关资源
      最近更新 更多