Home > Article > Backend Development > PHP determines whether the required parameters in the function exist
This article mainly introduces the relevant information about the detailed explanation of the example of PHP checking whether the function must pass parameters. Friends in need can refer to
The detailed explanation of the example of PHP checking whether the function must pass the parameter exists.
In actual PHP programming, the interface often receives parameters from the front end. Some of the parameters are not required and some are required. How to "check whether the required parameters of the function exist" "Woolen cloth? In order to solve this problem, you can refer to the following example method:
/** * @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; }
In actual application, call this method directly at the beginning of the application logic Just use the method.
Note: The error code is my custom error code. Be sure to change it to your own when using it.
Related recommendations:
How to use JSON as a function parameter
PHP method to dynamically obtain function parameters
The above is the detailed content of PHP determines whether the required parameters in the function exist. For more information, please follow other related articles on the PHP Chinese website!