php中的eval()函数
这里有一段代码,我不明白为什么输出是php代码:这是一个$string,里面有我的$name。这是一个杯子,里面有我的咖啡php中的eval()函数,php,eval,Php,Eval,这里有一段代码,我不明白为什么输出是php代码:这是一个$string,里面有我的$name。这是一个杯子,里面有我的咖啡 <?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"; //
<?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";
?>
因为输入字符串可能包含单引号,所以不能使用它们来开始和结束字符串
// 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";
?>
在这种情况下,您为什么需要eval
单引号内的变量不会被解释,而是放在双引号下
$str = "This is a $string with my $name in it."; //<--- Replaced single quotes to double quotes.
输出:
This is a cup with my coffee in it. This text can contain single quotes like this ' and also double quotes " too.
双引号字符串计算其中的所有变量。单个带引号的字符串不包含
现在来谈谈这句话
eval("\$str = \"$str\";");
首先,\$str
->转义了$,因此它是一个文本,而不是$str
变量
第二个$str
->->未转义$,整个字符串都在双引号中,因此这将成为
$str=“这是一个包含我的$name的$string。”
现在对这段PHP代码进行评估,它将右边的字符串分配给左边的变量。因此,$str
就变成了这是一杯我的咖啡
应避免进行评估。在第一次评估声明中:
eval("\$str = \"$str\";");
由于second$没有转义,并且在整个参数上使用双引号,因此second$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的值没有影响
希望这有帮助。:) PHP手册上说<代码>警告eval()语言构造非常危险,因为它允许执行任意PHP代码。因此,不鼓励使用它。如果您已经仔细验证了除了使用此构造之外没有其他选择,请特别注意,在未事先正确验证的情况下,不要将任何用户提供的数据传递给它。
$str=“$str”
只是将值赋给它已经拥有的变量,它不计算任何类型的PHP语法的内容。eval函数中编写的字符串不是PHP标记之间的语句吗?因此,以字符串形式编写的语句:(“\$str=\“$str\”;”);这与在php标记之间编写此语句不同:$str=“$str”???
eval('$str = "$str";');
$str = "$str";