PHP-如何在循环中创建变量名? [英] PHP - How Can I Create Variable Names Within a Loop?
问题描述
我的目标是创建一个创建变量名的循环.如:
My goal is to have a loop where variable names are created. Such as:
$variable1
$variable2
$variable3
$variable1
$variable2
$variable3
并在循环内分配值.例如,从1到7的for loop
会生成变量$variable1, $variable2, $variable3,
.etc,每个变量都有迭代器的值.
and assigned values within the loop. For instance, a for loop
from 1 to 7 produces the variables $variable1, $variable2, $variable3,
.etc, each with the value of the iterator.
推荐答案
有几种方法.一种是通过字符串和双精度$
,但是我不喜欢这种方法.程序员可以轻松地删除双精度$
(将其视为typeo).
There are several ways. One is via a string and a double $
, but I don't like this method. A programmer could easily remove the double $
(seeing it as a typeo).
for($i = 0; $i <= 7; $i++) {
$name = "variable{$i}";
$$name = "foo";
}
最好的方法是显式声明.
The best approach is the explicit statement.
for($i = 0; $i <= 7; $i++) {
${"variable$i"} = "foo";
}
使用显式内联字符串,毫无疑问您正在做什么.另一个PHP程序员不会错误地更改代码.
With the explicit inline string there is no doubt about the intent of what you're doing. Another PHP programmer will not alter the code by mistake.
这篇关于PHP-如何在循环中创建变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!