php檢查函數(shù)必傳參數(shù)是否存在的實(shí)例詳解
在php實(shí)際編程中,接口經(jīng)常會(huì)接收到前端傳來的參數(shù),其中有些參數(shù)不是必傳的,有些參數(shù)是必傳的,如何“檢查函數(shù)必傳參數(shù)是否存在”呢?為了解決該問題,可以參考以下的示例方法:
/** * @brief 檢測(cè)函數(shù)必傳參數(shù)是否存在 * @param $params array 關(guān)聯(lián)數(shù)組 要檢查的參數(shù) * @param array $mod array 索引數(shù)組 要檢查的字段 * @param array $fields array 索引數(shù)組 額外要檢查參數(shù)的字段 * @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; }
在實(shí)際應(yīng)用時(shí),于應(yīng)用程序邏輯的開始處,直接調(diào)用該方法即可。
注意:其中的錯(cuò)誤碼為我自定義的錯(cuò)誤碼,使用時(shí)務(wù)必改成你自己的。
以上就是php檢查函數(shù)必傳參數(shù)是否存在的實(shí)例詳解,如有疑問請(qǐng)留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
【網(wǎng)站聲明】本站除付費(fèi)源碼經(jīng)過測(cè)試外,其他素材未做測(cè)試,不保證完整性,網(wǎng)站上部分源碼僅限學(xué)習(xí)交流,請(qǐng)勿用于商業(yè)用途。如損害你的權(quán)益請(qǐng)聯(lián)系客服QQ:2655101040 給予處理,謝謝支持。