调用不存在的方法时重定向到其他方法

Ale*_*lex 3 php methods class

如果我调用$object->showSomething()并且该showSomething方法不存在,我会收到fata错误.没关系.

但我有一个show()方法,需要一个参数.我可以以某种方式告诉PHP show('Something');在遇到它时打电话$object->showSomething()吗?

Yos*_*shi 8

尝试这样的事情:

<?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();
Run Code Online (Sandbox Code Playgroud)

输出:

StuffMoreStuff and me tooEvenMoreStuff