Is $ this & # 8594; __ invoke (); 100% safe and valid in PHP?

// in class
public function test () {
    $this->__invoke();
}

$inst->test();

      

This test runs without error.

My question is, is there some reason why this shouldn't be done? Are there any corner cases, hidden caveats, or do they behave like any regular function / method?

+3


source to share


1 answer


This shouldn't work as there is no method in your class __invoke()

:

class SomeClass {
    public function test()
    {
        $this->__invoke();
    }
}

$inst = new SomeClass();
$inst->test();

      

http://3v4l.org/JOBXn .

If you are implementing __invoke()

this should work:



class SomeClass {
    public function __invoke()
    {
        var_dump('Invoke!');
    }

}

$inst = new SomeClass();
$inst();

      

http://3v4l.org/mpG5d .

Magic methods can be called directly, as you can see in the second test, but this is not a good idea in my opinion as they are kind of hooks and their code can be executed unexpectedly.

+3


source







All Articles