Search code examples
phpoopclassmethodscatch-all

PHP - catchall method in a class


Is there away to set up a class so that if a method is not defined, instead of throwing an error it would go to a catch-all function?

such that if i call $myClass->foobar(); but foobar was never set in the class definition, some other method will handle it?


Solution

  • Yes, it's overloading:

    class Foo {
        public function __call($method, $args) {
            echo "$method is not defined";
        }
    }
    
    $a = new Foo;
    $a->foo();
    $b->bar();
    

    As of PHP 5.3, you can also do it with static methods:

    class Foo {
        static public function __callStatic($method, $args) {
            echo "$method is not defined";
        }
    }
    
    Foo::hello();
    Foo::world();