14

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?

changokun
  • 1,563
  • 3
  • 20
  • 27

4 Answers4

20

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();
netcoder
  • 66,435
  • 19
  • 125
  • 142
  • 1
    +1 To add, it's *PHP* overloading, which is (inexplicably) a different use of the term than other OOP languages. – webbiedave Jun 06 '11 at 16:10
6

You want to use __call() to catch the called methods and their arguments.

Crashspeeder
  • 4,291
  • 2
  • 16
  • 21
6

Yes, you can use the __call magic method which is invoked when no suitable method is found. Example:

class Foo {
    public function __call($name, $args) {
         printf("Call to %s intercepted. Arguments: %s", $name, print_r($args, true));
    }
}

$foo = new Foo;
$foo->bar('baz'); // Call to bar intercepted. Arguments: string(3) 'baz'
alexn
  • 57,867
  • 14
  • 111
  • 145
1

Magic methods. In particular, __call().

Álvaro González
  • 142,137
  • 41
  • 261
  • 360