在这种情况下如何处理错误的参数类型


How to handle erroneous argument type in this situation?

我想使用stdClass来存储一些方法的选项,而不是传递巨大的变量列表(受javascript风格编码的启发)

然而,我想确保我总是得到stdClass的实例作为参数。我知道我可以在参数中添加一个提示(下面的gb::search),但是当我故意试图打破它时,我不确定如何处理错误。

提示吗?

class gb extends CI_Model {

protected $searchtypes = array('full','partial');
protected $endpoint = "https://local.endpoint";
function __construct() {
    parent::__construct();
    // sample search
    $options = new stdClass();
    $options->term = 'sample search';
    $options->type = 'full';
    $this->search($options);
}
function clean_term($term){
    $term = trim($term);
    return $term;
}
function search(stdClass $options){
    $term = $options->term;
    $type = $options->type;
    // make sure we're doing a valid search
    if (!$term || !in_array($type, $this->searchtypes)) {
        return false;
    }
    $term = $this->clean_term($term); // etc


}
它抛出的错误类似于:
A PHP Error was encountered
Severity: 4096
Message: Argument 1 passed to gb::search() must be an instance of stdClass, null given, called in /application/models/gb.php on line 20 and defined
Filename: models/gb.php
Line Number: 29
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: models/gb.php
Line Number: 31
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: models/gb.php
Line Number: 32

从CodeIgniter的角度来看,有什么想法吗?

如果我记得的话-错误输入的参数应该引发E_RECOVERABLE_ERROR,因此,它触发错误处理程序,但执行继续。所以,你基本上有两个选择。

当遇到E_RECOVERABLE_ERROR时,在错误处理程序中抛出异常。终止执行。

另一个-检查类型与instanceof stdClass和做你想做的-引发异常或返回一些东西。

UPDATE在您的情况下,您的框架(CI是CodeIgniter?)设置错误处理程序(某处使用set_error_handler)。因此,在记录或打印错误消息之后,执行将继续。(如果没有处理程序,您将得到致命错误)。只需手动测试参数类型:

function search(stdClass $options){
  // test type for sure, because of recoverable error
  if (!($options instanceof stdClass)) {
    return false; // or throw new InvalidArgumentException('Parameter should be instance of stdClass');
  }
  $term = $options->term;
  $type = $options->type;
  // make sure we're doing a valid search
  if (!$term || !in_array($type, $this->searchtypes)) {
    return false;
  }
  $term = $this->clean_term($term); // etc
}