引号 - 关于php eval( )函数 和 实际代码执行的 结果不一致
大家讲道理
大家讲道理 2017-04-11 09:09:03
0
4
756
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函数的时候直接加双引号却不行呢!请问这个问题是出在哪里?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(4)
洪涛

$str = 'This is a $string with my $name in it.';单引号不解析变量

Peter_Zhu

eval的时候,This is a $string with my $name in it.当做一条表达式, ""内的$var自然会被当做变量处理;
如果下面的那种情况改成

$str = "This is a $string with my $name in it.";
echo $str. "\n";

输出也就一致了。
至于你后面的$str = "$str"; 这里只是普通的赋值。

洪涛

双引号内的变量解析不能“递归”

阿神

教你一招:双引号+花括号

$string = 'cup';
$name = 'coffee';
$str = "This is a {$string} with my {$name} in it.";
echo $str;

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template