在php实际编程中,经常会遇到“检查函数必传参数是否存在”的问题,为了解决该问题,可以参考以下的示例方法:
/**
* @brief 检测函数必传参数是否存在
* @param $params array 关联数组 要检查的参数
* @param array $mod array 索引数组 要检查的字段
* @param array $fields array 索引数组 额外要检查参数的字段
* @return bool
* @throws Exception
*/
private function checkParamsExists($params, $mod = [], $fields = [])
{
if (empty($params)) {
throw new \Exception(Error::ERROR_INVALID_PARAMETER_MSG . ',[checkParamsExists] the array of params is empty', Error::ERROR_INVALID_PARAMETER_CODE);
}
$params = is_array($params) ? $params : [$params];
if ($fields) {
$fields = array_flip($fields);
$params = array_merge($params, $fields);
$params_count = count($params);
$mod_count = count($mod);
if ($params_count > $mod_count) { //参数个数 大于 要检测的字段个数
throw new \Exception(Error::ERROR_INVALID_PARAMETER_MSG . ',[checkParamsExists]the size of params ' . json_encode($params) . ' is bigger than the size of mod ' . json_encode($mod) , Error::ERROR_INVALID_PARAMETER_CODE);
}
} else {
$params_count = count($params);
$mod_count = count($mod);
if ($params_count > $mod_count) { //参数个数 大于 要检测的字段个数
throw new \Exception(Error::ERROR_INVALID_PARAMETER_MSG . ',[checkParamsExists]the size of params ' . json_encode($params) . ' is bigger than the size of mod ' . json_encode($mod) , Error::ERROR_INVALID_PARAMETER_CODE);
}
}
foreach ($mod as $mod_key => $mod_value) {
if (!array_key_exists($mod_value, $params)) {
throw new \Exception(Error::ERROR_INVALID_PARAMETER_MSG . ',[checkParamsExists]' . json_encode($params) . ' do not have key field(' . $mod_value . ')', Error::ERROR_INVALID_PARAMETER_CODE);
}
}
return true;
}在实际应用时,于应用程序逻辑的开始处,直接调用该方法即可。注意:其中的错误码为我自定义的错误码,使用时务必改成你自己的。