在调用不存在的方法时重定向到其他方法 [英] redirecting to other methods when calling non-existing methods

查看:127
本文介绍了在调用不存在的方法时重定向到其他方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我调用 $ object-> showSomething() showSomething fata错误。没关系。

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

但我有一个接受参数的 show()方法。我可以以某种方式告诉PHP当遇到 $ object-> showSomething() show('Something'); >

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

推荐答案

尝试如下:

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

输出

StuffMoreStuff和我tooEvenMoreStuff

这篇关于在调用不存在的方法时重定向到其他方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆