【问题标题】:redirecting to other methods when calling non-existing methods调用不存在的方法时重定向到其他方法
【发布时间】:2011-06-07 16:39:20
【问题描述】:

如果我调用$object->showSomething() 并且showSomething 方法不存在,我会收到一个致命错误。没关系。

但我有一个带有参数的show() 方法。我可以告诉 PHP 在遇到$object->showSomething() 时调用show('Something'); 吗?

【问题讨论】:

  • 解决方法是通过__call 捕获此类函数调用并重定向到替代函数。如果show* 是您唯一的特殊情况,那也没关系;如果您需要在 camelCase 上拆分其他方法/参数,那么这就不那么出色了(会违反语言语义,因为 PHP 标识符实际上不区分大小写)。
  • 我明白了。 __call() 仅在找不到方法时运行?
  • 是的,它可以作为后备。真正的方法有优先权。如果没有找到任何东西,__call 将处理它。

标签: php class methods


【解决方案1】:

试试这样的:

<?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 and me tooEvenMoreStuff

【讨论】:

  • 可能想用 } else { trigger_error('Unknown function '.__CLASS__.':'.$method, E_USER_ERROR); } 关闭 __call 函数,否则可能会导致以后很难调试类...
  • @Wrikken 你说得对,我在那里有点懒惰。 ;) ... 更新了示例代码。
【解决方案2】:

不一定只是show.... 方法,而是任何方法,是的,使用__call。检查函数本身要求的方法。

【讨论】:

    【解决方案3】:

    您可以使用函数method_exists()。示例:

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

    【讨论】:

      猜你喜欢
      • 2017-06-25
      • 2018-08-26
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      • 2012-05-01
      • 2022-01-18
      • 2013-02-08
      相关资源
      最近更新 更多