[英]Creating a user defined function
我应该创建一个使用 2 个参数的函数。 这两个参数都是字符串。 其中一个参数是 text ,另一个参数是一个字母, A
或B
。 如果是A
,我需要使用文本的内置 PHP 函数将大小写更改为大写。 如果是B
,我需要使用文本的内置 PHP 函数将大小写更改为小写。
我知道我必须使用 elseif 语句。
function paint($case, $str)
{
if $case = A echo $sentence ($str);
else echo upper($str);
}
$sentence = "Placeholder text here.";
paint("a", $sentence);
paint("b", $sentence);
您应该使用switch..case
语句
function paint($case, $str)
{
switch (strtolower($case))
{
case 'a': $str = strtoupper($str);
break;
case 'b': $str = strtolower($str);
break;
}
echo $str;
}
$sentence = "Placeholder text here.";
paint("a", $sentence); // PLACEHOLDER TEXT HERE.
paint("b", $sentence); // placeholder text here.
paint("nonsense", $sentence); // Placeholder text here.
或者,如果您想在既没有给出“a”也没有给出“b”的情况下抛出异常,请将switch
块更改为:
switch (strtolower($case))
{
case 'a': $str = strtoupper($str);
break;
case 'b': $str = strtolower($str);
break;
default :
throw new \InvalidArgumentException('First argument of function "' . __FUNCTION__ . '" is expected to be a string either "a" or "b".');
}
switch
.. case
结构是多个if
.. elseif
.. else
语句的另一种形式,除了条件作为入口点。 如果您不使用显式break
语句,则执行将失败到下一个案例。 如果没有其他情况匹配,则default
是入口点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.