php参数检查,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);

$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;

}在实际应用时,于应用程序逻辑的开始处,直接调用该方法即可。注意:其中的错误码为我自定义的错误码,使用时务必改成你自己的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值