代码之家  ›  专栏  ›  技术社区  ›  smarber

如何调用类的可调用属性

php
  •  0
  • smarber  · 技术社区  · 4 年前

    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
    }
    

    0 回复  |  直到 4 年前
        1
  •  1
  •   Barmar    4 年前

    $this->a($t) 模棱两可。这可能意味着打电话给 a 方法 $this 有争论吗 $t ,或获取 财产 并且(如果它是可调用的)用参数调用它 美元 .