可变变量不好用吗? [英] variable variables bad practice to use?
问题描述
I have just read the post is it bad practice to use variable variables in php in the following fashion? explaining why they are bad to use in with classes however, i have to create dynamic variables to be sorted
例如:
$array =
array(
array("Line 1","Line 2","Line 3"),
array("Line 1","Line 2","Line 3"),
array("Line 1","Line 2","Line 3"),
)
$i = 1;
foreach($array as $item){
$string = "Item".$i;
$$string = $item[0]."some code".$item[1]."some code".$item[2]."some code";
}
我知道每个辅助数组中将永远只有3个数组值,并且只有3个数组.
i know that there will only ever be 3 array values in each secondary array and there will only ever be 3 arrays.
有没有一种方法可以使用更好的实践"代码来实现?还是我忽略的更简单的方法?
is there a way to achieve this using "better practice" code? or a simpler way which i have overlooked?
提前感谢您的时间
推荐答案
这应该很好:
$newArray = array_map(function (array $item) {
return $item[0]."some code".$item[1]."some code".$item[2]."some code";
}, $array);
var_dump($newArray);
我根本看不到需要单独的变量的地方.
I don't see where separate variables are needed at all.
如果您只是连续动态地对变量编号($item1
,$item2
等),则您试图保留动态数量的元素.这正是数组的用途:$items[0]
,$items[1]
等.
If you just continuously number variables dynamically ($item1
, $item2
etc.), you're trying to hold a dynamic number of elements. That's exactly what arrays are for: $items[0]
, $items[1]
etc.
这篇关于可变变量不好用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!