简体   繁体   English

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

[英]How can I make PHP handle functions' overloading errors?

Lets assume I have a class called Form . 假设我有一个叫做Form的类。 This class uses the magic method __call() to add fields to itself like so: 此类使用魔术方法__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

    }

  }  

}

My problem is that I can't figure out how to make PHP handle the calls to undefined methods in it's default way. 我的问题是我无法弄清楚如何使PHP以默认方式处理对未定义方法的调用。 Of course, the default behavior can be mimicked in many ways, for example I use the following code right now: 当然,可以通过多种方式模仿默认行为,例如,我现在使用以下代码:

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

But I don't like this solution because the error itself or its level might change in the future, so is there a better way to handle this in PHP? 但是我不喜欢这种解决方案,因为错误本身或其级别将来可能会更改,因此有没有更好的方法来用PHP处理呢?

Update Seems like my question is a little vague, so to clarify more... How can I make PHP throw the default error for undefined methods without the need to supply the error and it's level? 更新似乎我的问题有点含糊,因此请澄清更多...我如何才能使PHP为未定义方法抛出默认错误, 无需提供错误及其级别? The following code won't work in PHP, but it's what I'm trying to do: 以下代码在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);

If anyone is familiar with ruby, this can be achieved by calling the super method inside method_missing . 如果有人熟悉ruby,可以通过在method_missing内部调用super方法来实现。 How can I replicate that in PHP? 如何在PHP中复制它?

Use exceptions, that's what they're for 使用异常,这就是它们的用途

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);
    }
}

This is then trivially easy to catch 那么这很容易抓住

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM