如何调用类的可调用属性

  • 本文关键字:调用 属性 何调用 php
  • 更新时间 :
  • 英文 :


我不明白为什么一个类属性是这样的可调用对象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
}

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

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

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

最新更新