开发者

redirecting to other methods when calling non-existing methods

If I call $object->showSomething() and the showSomething method doesn't exist I get a fata error. That's OK.

But I have a show() method that takes a argument. Can I开发者_StackOverflow中文版 somehow tell PHP to call show('Something'); when it encounters $object->showSomething() ?


Try something like this:

<?php
class Foo {

    public function show($stuff, $extra = '') {
        echo $stuff, $extra;
    }

    public function __call($method, $args) {
        if (preg_match('/^show(.+)$/i', $method, $matches)) {
            list(, $stuff) = $matches;
            array_unshift($args, $stuff);
            return call_user_func_array(array($this, 'show'), $args);   
        }
        else {
            trigger_error('Unknown function '.__CLASS__.':'.$method, E_USER_ERROR);
        }
    }
}

$test = new Foo;
$test->showStuff();
$test->showMoreStuff(' and me too');
$test->showEvenMoreStuff();
$test->thisDoesNothing();

Output:

StuffMoreStuff and me tooEvenMoreStuff


Not necessarily just the show.... methods, but any method, yes, use __call. Check for the method asked in the function itself.


You can use the function method_exists(). Example:

class X {
    public function bar(){
        echo "OK";
    }
}
$x = new X();
if(method_exists($x, 'bar'))
    echo 'call bar()';
else
    echo 'call other func';
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜