我如何命名这些php变量

时间:2011-09-14 05:26:03

标签: php

我想使用for循环来创建多个汽车......他们的名字是$var1$var15。我怎么做?我正在做$$var.$i,但它没有用。

for($i=1; $i <= 15; $i++){
   $$var.$i = 'this is the content of var'.$i;
}

1 个答案:

答案 0 :(得分:4)

如果你想这样做,那么你必须做${$var . $i}。现在它被解释为($$var).$i

然而,这是非常糟糕的风格。相反,您应该使用数组 [php docs] 来存储值:

$var = array();
for($i=1; $i <= 15; $i++){
    $var[$i] = 'This is the content of $var['.$i.'].';
}

var_export($var);
输出:
array (
  1 => 'This is the content of $var[1].',
  2 => 'This is the content of $var[2].',
  3 => 'This is the content of $var[3].',
  4 => 'This is the content of $var[4].',
  5 => 'This is the content of $var[5].',
  6 => 'This is the content of $var[6].',
  7 => 'This is the content of $var[7].',
  8 => 'This is the content of $var[8].',
  9 => 'This is the content of $var[9].',
  10 => 'This is the content of $var[10].',
  11 => 'This is the content of $var[11].',
  12 => 'This is the content of $var[12].',
  13 => 'This is the content of $var[13].',
  14 => 'This is the content of $var[14].',
  15 => 'This is the content of $var[15].',
)

这更有效,而且通常更安全。