php中的eval()函数

时间:2014-01-17 13:10:25

标签: php eval

这里是一个代码,我不明白为什么输出的PHP代码:这是一个带有$ name的$ string。这是一杯我的咖啡。

<?php
$string = 'cup';
$name = 'coffee';

$str = 'This is a $string with my $name in it.';

// will not echo the value of the strings variable because there in ' '
echo $str. "\n";

// this function is like writing the php code outside of it
// it gets a string with php statments (;) 
// because the code is written in a string
// if it is written it double quotes you have to escape $ and " 
// and if it is written in single quotes you have to escape '

eval("\$str = \"$str\";");

//it is not like this, why?????
//eval('$str = "$str";');

// and not like this, why???????
//$str = "$str" ;

echo $str. "\n";
?>

为什么不是声明:eval('$ str =“$ str”;');或声明:$ str =“$ str”;做同样的事情:eval(“\ $ str = \”$ str \“;”);在此代码中

4 个答案:

答案 0 :(得分:0)

//it is not like this, why?????
//eval('$str = "$str";');

因为输入字符串可能包含单引号,所以您不能使用它们来开始和结束字符串。

// and not like this, why???????
//$str = "$str" ;

因为你想要评估一个字符串,而且上面没有字符串。

我没有看到这个例子的意思,只是使用双引号:

<?php
$string = 'cup';
$name = 'coffee';

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

echo $str. "\n";
?>

答案 1 :(得分:0)

为什么在这种情况下你需要eval

单引号内的变量不会被解释,而是将它放在双引号下。

$str = "This is a $string with my $name in it."; //<--- Replaced single quotes to double quotes.

其次..如果您真的担心逃避,为什么不使用 HEREDOC 语法

<?php
$string = 'cup';
$name = 'coffee';

$cont=<<<ANYCONTENT
This is a $string with my $name in it. This text can contain single quotes like this ' and also double quotes " too.

ANYCONTENT;

echo $cont;

输出:

This is a cup with my coffee in it. This text can contain single quotes like this ' and also double quotes " too. 

答案 2 :(得分:0)

双引号字符串计算其中的所有变量。单引号字符串不会。

现在发表声明

eval("\$str = \"$str\";");

首先\$str - &gt; $是转义的,所以它是一个文字,而不是$str变量

$str - &gt; $没有被转义,整个字符串都是双引号,所以这将成为

$str = "This is a $string with my $name in it."

现在评估这个PHP代码,它将右边的字符串分配给左边的变量。因此$str成为This is a cup with my coffee in it

应避免使用评估。

答案 3 :(得分:0)

在第一个eval声明中:

eval("\$str = \"$str\";");

由于第二个$未被转义,并且您在整个争论中使用双引号,因此第二个$ str的值传递给eval,并且eval的参数变为:

eval("\$str = \"This is a $string with my $name in it.\";");

,在评估时,变为:

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

指定'这是一杯加入我的咖啡。'到$ str。

在第二个评估中:

eval('$str = "$str";');

评估的陈述是:

$str = "$str";

与您的第三个陈述相同。执行此语句时,它会将非字符串转换为字符串。在这种情况下,$ str已经是一个字符串,因此该语句对$ str。

的值没有影响

希望这会有所帮助。 :)

相关问题