(PHP 4, PHP 5)
eval — 把字符串作为PHP代码执行
把字符串 code
作为PHP代码执行。
The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.
code
需要被执行的字符串
代码不能包含打开/关闭 PHP tags。比如,'echo "Hi!";' must be passed instead of '<? echo "Hi!"; >'. It is still possible to leave and reenter PHP mode though using the appropriate PHP tags, e.g. 'echo "In PHP mode!"; ?>In HTML mode!<? echo "Back in PHP mode!";'.
Apart from that the passed code must be valid PHP. This includes that all statements must be properly terminated using a semicolon. 'echo "Hi!"' for example will cause a parse error, whereas 'echo "Hi!";' will work.
return 语句会立即中止当前字符串的执行。
The code will be executed in the scope of the code calling eval(). Thus any variables defined or changed in the eval() call will remain visible after it terminates.
eval() 返回 NULL
,除非在执行的代码中 return 了一个值,函数返回传递给 return 的值。
如果在执行的代码中有一个解析错误,eval() 返回
FALSE
,之后的代码将正常执行。无法使用 set_error_handler() 捕获 eval() 中的解析错误。
Example #1 eval() 例子 - 简单的文本合并
<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
?>
以上例程会输出:
This is a $string with my $name in it. This is a cup with my coffee in it.