如何让PHP处理函数的重载错误?

时间:2011-08-18 23:35:27

标签: php error-handling

假设我有一个名为Form的类。此类使用魔术方法__call()向其自身添加字段,如下所示:

<?php
class Form {

  private $_fields = array();

  public function __call($name, $args) {

    // Only allow methods which begin with 'add'
    if ( preg_match('/^add/', $name) ) {

       // Add a new field

    } else {

       // PHP throw the default 'undefined method' error

    }

  }  

}

我的问题是我无法弄清楚如何让PHP以默认方式处理对未定义方法的调用。当然,可以通过多种方式模仿默认行为,例如我现在使用以下代码:

trigger_error('Call to undefined method ' . __CLASS__ . '::' . $function, E_USER_ERROR);

但是我不喜欢这个解决方案,因为错误本身或它的级别将来可能会改变,那么在PHP中有更好的方法来处理它吗?

更新 似乎我的问题有点模糊,所以要澄清更多...如何让PHP抛出未定义方法的默认错误没有需要提供错误及其级别?以下代码在PHP中不起作用,但这正是我想要做的:

// This won't work because my class is not a subclass. If it were, the parent would have             
// handled the error 
parent::__call($name, $args);

// or is there a PHP function like...
trigger_default_error(E_Undefined_Method);

如果有人熟悉ruby,可以通过调用super内的method_missing方法来实现。我怎样才能在PHP中复制它?

2 个答案:

答案 0 :(得分:1)

使用例外,这就是他们的目的

public function __call($name, $args) {
   // Only allow methods which begin with 'add'
    if ( preg_match('/^add/', $name) ) {
       // Add a new field
    } else {
       throw new BadMethodCallException('Call to undefined method ' . __CLASS__ . '::' . $name);
    }
}

这很容易理解

try {
    $form->foo('bar');
} catch (BadMethodCallException $e) {
    // exception caught here
    $message = $e->getMessage();
}

答案 1 :(得分:0)

如果您想更改错误级别,只需在必要时进行更改或添加if语句而不是E_USER_ERROR