Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 367
changokun Avatar asked Jun 06 '11 16:06

changokun


4 Answers

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();
like image 131
netcoder Avatar answered Nov 15 '22 01:11

netcoder


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

like image 35
Crashspeeder Avatar answered Nov 15 '22 00:11

Crashspeeder


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'
like image 6
alexn Avatar answered Nov 14 '22 23:11

alexn


Magic methods. In particular, __call().

like image 1
Álvaro González Avatar answered Nov 14 '22 23:11

Álvaro González