Home > Backend Development > PHP Tutorial > PHP determines whether the required parameters in the function exist

PHP determines whether the required parameters in the function exist

墨辰丷
Release: 2023-03-26 14:50:01
Original
2841 people have browsed it

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; 
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template