redirecting to other methods when calling non-existing methods

后端 未结 3 801
甜味超标
甜味超标 2021-01-14 16:18

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

相关标签:
3条回答
  • 2021-01-14 17:11

    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

    0 讨论(0)
  • 2021-01-14 17:15

    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 讨论(0)
  • 2021-01-14 17:16

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

    0 讨论(0)
提交回复
热议问题