开发者

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 ca开发者_Go百科tch-all function?

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


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();


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


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'


Magic methods. In particular, __call().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜