Search code examples
phpmagic-methods

How to create my own PHP magic method names?


Some frameworks have their own magic methods names, such as

$player->findByName('Lionel Messi')

which results in a simple SELECT * FROM players WHERE name='Lionel Messi' query. In PHP how can I make similar methods? Do they somehow catch the global MethodNotFoundException?


Solution

  • Use __call magic method. Read more about it in docs, that is all you need.

    http://php.net/manual/en/language.oop5.magic.php

    public function __call($name, $args) {
        // TODO: Parse called method name and run query if needed
    }