Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/236.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
参数必须包含一个特定的值-PHP_Php_String_Function_Arguments - Fatal编程技术网

参数必须包含一个特定的值-PHP

参数必须包含一个特定的值-PHP,php,string,function,arguments,Php,String,Function,Arguments,如何创建一个PHP函数,该函数可能只包含一个特定值,如值可能仅为: temperature_unit('C'); 或: 如果愿意,可以用调用来替换异常 您还可以使用switch语句并在默认情况下引发异常: function temperature_unit($type) { switch ($type) { case 'F': // do work in F break; case 'C': // do work in C b

如何创建一个PHP函数,该函数可能只包含一个特定值,如值可能仅为:

temperature_unit('C');
或:

如果愿意,可以用调用来替换异常

您还可以使用switch语句并在默认情况下引发异常:

function temperature_unit($type) {
  switch ($type) {
    case 'F':
      // do work in F
      break;
    case 'C':
      // do work in C
      break;
    default:
      throw new InvalidArgumentException('$type must be C or F');
  }
}

现在我有另一个问题,我能做些什么来检查
$type
F
还是
C
?@Me123:如果你只检查它是否等于一个值,只需使用一个相等运算符:
如果($type=='F')
,或者查看我更新的答案以获取另一个示例。
function temperature_unit($type) {
  if (!in_array($type, array('C', 'F'), true))
    throw new InvalidArgumentException('$type must be C or F');
  // rest of your function
}
function temperature_unit($type) {
  switch ($type) {
    case 'F':
      // do work in F
      break;
    case 'C':
      // do work in C
      break;
    default:
      throw new InvalidArgumentException('$type must be C or F');
  }
}