在此 PHP代码中,我想将静态值定义为多个变量 而将字符串连接到其父变量,如下面的代码
$Alpha = "Alpha-";
$Beta = "Beta-";
$Gamma = "Gamma-";
function func($vars, $number, $letter) {
switch ($number) {
case 1:
foreach ($vars as $var) {
$var .= "1";
}
break;
case 2:
foreach ($vars as $var) {
$var .= "2";
}
break;
case 3:
foreach ($vars as $var) {
$var .= "3";
}
}
switch ($letter) {
case "a":
foreach ($vars as $var) {
$var .= "A";
}
break;
case "b":
foreach ($vars as $var) {
$var .= "B";
}
break;
case "c":
foreach ($vars as $var) {
$var .= "C";
}
}
return $var;
}
func([$Alpha, $Beta, $Gamma], 1, "a");
$Alpha .= "-haEND";
$Beta .= "-taEND";
$Gamma .= "-maEND";
echo $Alpha;
echo '<br>';
echo $Beta;
echo '<br>';
echo $Gamma;
我希望结果是
α-1A-haEND
β-1A-taEND
伽玛-1A-maEND
但我没有得到 1A
答案 0 :(得分:1)
您正在尝试更新变量副本的值(在每个foreach中)。要更新该值,您必须在循环中通过引用传递它们。
然后,您没有使用返回值。
你可以尝试这样的事情。请注意foreach中的&
,返回的使用以及list()
从数组中提取数据。
$Alpha = "Alpha-";
$Beta = "Beta-";
$Gamma = "Gamma-";
function func($vars, $number, $letter) {
switch ($number) {
case 1:
foreach ($vars as &$var) {$var .= "1"; }
break;
case 2:
foreach ($vars as &$var) {$var .= "2"; }
break;
case 3:
foreach ($vars as &$var) {$var .= "3"; }
}
switch ($letter) {
case "a":
foreach ($vars as &$var) {$var .= "A"; }
break;
case "b":
foreach ($vars as &$var) {$var .= "B"; }
break;
case "c":
foreach ($vars as &$var) {$var .= "C"; }
}
return $vars;
}
$arr = func([$Alpha, $Beta, $Gamma], 1, "a");
list($Alpha, $Beta, $Gamma) = $arr ;
$Alpha .= "-haEND";
$Beta .= "-taEND";
$Gamma .= "-maEND";
echo $Alpha;
echo '<br>';
echo $Beta;
echo '<br>';
echo $Gamma;
输出:
Alpha-1A-haEND
Beta-1A-taEND
Gamma-1A-maEND
答案 1 :(得分:1)
你在这里有很多重复的代码 - 没有必要使用六个单独的循环来为一些字符串添加数字和字母。
PHP的array_walk
方法允许您将一个用户定义的回调应用于数组的每个成员,这可以大大减少这一点,并且如果您需要,还可以不需要添加其他的case语句展开支持的数字/字母集:
$Alpha = "Alpha-";
$Beta = "Beta-";
$Gamma = "Gamma-";
$values = [&$Alpha, &$Beta, &$Gamma];
$number = 1;
$letter = 'a';
array_walk($values, function (&$item) use ($number, $letter) {
$item .= $number . strtoupper($letter);
});
$Alpha .= "-haEND";
$Beta .= "-taEND";
$Gamma .= "-maEND";
正如@Syscall所提到的,重要的区别在于元素通过引用传递给函数 - 您的原始代码是修改副本,而不是原件。