eval()
在php中这个eval()
函数是将字符串作为代码来执行
于是下面这段代码
<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
$str = "$str";
echo $str. "\n";
输出为
This is a $string with my $name in it. This is a cup with my coffee in it.
那么现在我用实际代码代替eval()
函数
<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
$str = "$str";
echo $str. "\n";
这输出为
This is a $string with my $name in it. This is a $string with my $name in it.
其实我知道单引号的不解析变量,我只是不明白为什么使用eval()
函数的时候单引号中的变量被解析了!是因为在$str外加了双引号吗?如果是,那么在不使用eval函数的时候直接加双引号却不行呢!请问这个问题是出在哪里?
$str = 'This is a $string with my $name in it.';
单引号不解析变量eval的时候,This is a $string with my $name in it.当做一条表达式, ""内的$var自然会被当做变量处理;
如果下面的那种情况改成
输出也就一致了。
至于你后面的$str = "$str"; 这里只是普通的赋值。
双引号内的变量解析不能“递归”
教你一招:双引号+花括号
$string = 'cup';
$name = 'coffee';
$str = "This is a {$string} with my {$name} in it.";
echo $str;