参数必须包含一个特定的值-PHP
如何创建一个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
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');
}
}