0

I do not understand why a class property which is an invokable object this way 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);

This will result in an error:

<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 />

To make this work, I had to change the method yo as follows:

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

I could not find any explanation online. Any ideas?

smarber
  • 4,829
  • 7
  • 37
  • 78

1 Answers1

3

$this->a($t) is ambiguous. It could either mean call the a method of $this with the argument $t, or get the a property of $this and (if it's callable) call that with the argument $t.

Since method calling is much more common than properties containing callable objects, it defaults to the former interpretation. You need parentheses to override that parse.

Barmar
  • 741,623
  • 53
  • 500
  • 612