相關(guān)關(guān)鍵詞
關(guān)于我們
最新文章
php檢查函數(shù)必傳參數(shù)是否存在的實例詳解
php檢查函數(shù)必傳參數(shù)是否存在的實例詳解
在php實際編程中,接口經(jīng)常會接收到前端傳來的參數(shù),其中有些參數(shù)不是必傳的,有些參數(shù)是必傳的,如何“檢查函數(shù)必傳參數(shù)是否存在”呢?為了解決該問題,可以參考以下的示例方法:
/** * @brief 檢測函數(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; }