我目前正在开发一个框架,遇到了问题......当有人调用框架中的函数时,如何处理参数类型不正确的情况?
例如:
你会像这样使用它:
基本上会检查第一个和第二个参数是否为字符串,第三个参数是整数或浮点数。您可以组合任何类型的 'string、int、array、object' 等,所有有效类型都从 gettype 中获取。
/* 已知的错误 */ null 是一种类型,无法确定它是否应该是这样 如果输入类名,则不会检查实例,而只会执行类型检查 还没有找到触发错误的好方法...... 嗯
这就是我要说的了,这些错误很容易修复 :D
例如:
// Title is expected to be string, comment_num is expected to be int
function example1($title, $comment_num) {
// Doesnt throw error, just converts type
$title = (string) $title;
$comment_num = (int) $comment_num;
}
或者
// Title is expected to be string, comment_num is expected to be int
function example2($title, $comment_num) {
if (!is_string($title)) {
trigger_error('String expected for first parameter', E_USER_WARNING);
return;
}
if (!is_string($title)) {
trigger_error('Int expected for second parameter', E_USER_WARNING);
return
}
}
还是混合使用的方式比较好?抛出错误并强制转换类型?
最好的方法是什么?我计划发布它,所以不只是我会用它,因此我也要考虑到其他人。谢谢。
编辑!!!
所以我决定给出答案,但我也想发布我编写的代码,它可以让我快速检查类型。它有点粗糙,但足够好用了。
function __type_check($params) {
if (count($params) < 1) {
return;
}
$types = func_get_args();
array_shift($types);
$backtrace = debug_backtrace();
$backtrace = $backtrace[1];
$global_types = array(
'bool' => 'boolean',
'int' => 'integer',
'float' => 'double'
);
$error = false;
for ($i = 0, $j = count($types); $i < $j; ++$i) {
if (strpos($types[$i], ',') === false) {
$type = strtolower($types[$i]);
if (isset($global_types[$type])) {
$type = $global_types[$type];
}
if (gettype($params[$i]) != $type) {
$error = true;
break;
}
} else {
$current_types = array_map('trim', explode(',', $types[$i]));
foreach ($current_types as $type) {
$type = strtolower($type);
if (isset($global_types[$type])) {
$type = $global_types[$type];
}
if (gettype($params[$i]) == $type) {
continue 2;
}
}
$error = true;
break;
}
}
if ($error) {
trigger_error($backtrace['function'] . '() expects parameter ' . ($i + 1) . ' to be ' . $types[$i] . ', ' . gettype($params[$i]) . ' given', E_USER_WARNING);
return false;
}
return true;
}
你会像这样使用它:
function string_manipulation($str, $str2, $offset = 1) {
if (!__type_check(func_get_args(), 'string', 'string', 'int,float')) {
return false;
}
// do manipulation here
}
基本上会检查第一个和第二个参数是否为字符串,第三个参数是整数或浮点数。您可以组合任何类型的 'string、int、array、object' 等,所有有效类型都从 gettype 中获取。
/* 已知的错误 */ null 是一种类型,无法确定它是否应该是这样 如果输入类名,则不会检查实例,而只会执行类型检查 还没有找到触发错误的好方法...... 嗯
这就是我要说的了,这些错误很容易修复 :D
trigger_error
,而应该抛出异常(throw exceptions)。它们更加灵活且更易有效地处理。 - ircmaxellfopen()
是我最喜欢的例子)。我认为,如果你可以在不丢失信息的情况下转换参数,请这么做;如果不能,则返回一个错误代码。 - staticsan