question about php eval() function
i 开发者_开发技巧defined a couple of variables: $day_0, $day_1...$day_8 and need to build a string with those days variable embedded in the string, here is what i did;
for($i = 0; $i <=8; $i++) {
$d = 'day_'.$i;
$day = eval($($d));echo $day;
$cmd_line .= 'INPUT'.$i.'='.$quote.$day.$quote.$space;
}
but php always complained
syntax error, unexpected '(', expecting T_VARIABLE or '$'
what's wrong with it? Thanks.
No need to use eval
:
for($i = 0; $i <=8; $i++) {
$day = ${'day_' . $i};
echo $day;
$cmd_line .= 'INPUT'.$i.'='.$quote.$day.$quote.$space;
}
See the PHP Documentation for more information on variable variables.
A safer and easier solution would be to use:
$d = 'day_'.$i;
$day = $$d;
Why not just use $$
?
for($i = 0; $i <=8; $i++) {
$d = 'day_'.$i;
$day = $$d; //this will point to $day_0 ...
echo $day;
$cmd_line .= 'INPUT'.$i.'='.$quote.$day.$quote.$space;
}
I don't suggest eval()
but if you want to use it pass valid php code as eval()
parameter (string).
Example:
$d = 'day_1';
$phpcode = "\${$d}='something';";
$day = eval($phpcode);
echo $day_1;
This will print out string something
assigned to new variable $day_1
.
Don't forget to add ;
at the and of every line you want to evaluate using eval()
function.
Array would be better solution.
精彩评论