我不明白为什么一个类属性是这样的可调用对象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->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
调用$this
的a
方法,或者获取$this
的a
属性并(如果它是可调用的(用参数$t
调用它。
由于方法调用比包含可调用对象的属性更常见,因此它默认为前一种解释。您需要圆括号来覆盖该解析。