Redirecting to other methods when calling non-existent methods

If I call $object->showSomething()and the method showSomethingdoes not exist, I get a fata error. This is normal.

But I have a method show()that takes an argument. Can I somehow tell PHP to call show('Something');when it encounters $object->showSomething()?

+3
source share
3 answers

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

+7
source

Not only methods show...., but any method, yes, use __ call . Check the method specified in the function itself.

+2
source

You can use the method_exists () function . Example:

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

All Articles