我想使用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的角度来看待这个问题?
答案 0 :(得分:1)
如果我记得 - 错误输入的参数应该引发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
}