首页 > 语言 > PHP > 正文

php检查函数必传参数是否存在的实例详解

2024-05-04 23:59:48
字体:
来源:转载
供稿:网友

php检查函数必传参数是否存在的实例详解

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

在实际应用时,于应用程序逻辑的开始处,直接调用该方法即可。

注意:其中的错误码为我自定义的错误码,使用时务必改成你自己的。

以上就是php检查函数必传参数是否存在的实例详解,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


注:相关教程知识阅读请移步到PHP教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选