redirecting to other methods when calling non-exis

2019-02-19 08:19发布

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 somehow tell PHP to call show('Something'); when it encounters $object->showSomething() ?

3条回答
Viruses.
2楼-- · 2019-02-19 08:36

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

查看更多
Root(大扎)
3楼-- · 2019-02-19 08:56

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';
查看更多
三岁会撩人
4楼-- · 2019-02-19 09:00

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

查看更多
登录 后发表回答