Search code examples
phpclassmagic-methods

Is $this->__invoke(); 100% safe and valid in PHP?


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

$inst->test();

This test runs without any error.

My question: is there some reason why this should not be done? Are there any corner cases, hidden caveats, or does it behave like any regular function/method?


Solution

  • That should not work since there is no __invoke() method in your class:

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

    http://3v4l.org/JOBXn.

    If you implement __invoke(), that 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 in my opinion it is not a good idea since they are some kind of hooks and their code could be executed unexpectedly.