(PHP 4, PHP 5)
eval — 把字符串作為PHP代碼執(zhí)行
說明
mixed eval ( string$code
)
把字符串 code
作為PHP代碼執(zhí)行。
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.
參數(shù)
code
需要被執(zhí)行的字符串
代碼不能包含打開/關(guān)閉 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 語句會立即中止當(dāng)前字符串的執(zhí)行。
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
,除非在執(zhí)行的代碼中 return 了一個(gè)值,函數(shù)返回傳遞給 return 的值。
如果在執(zhí)行的代碼中有一個(gè)解析錯(cuò)誤,eval() 返回
FALSE
,之后的代碼將正常執(zhí)行。無法使用 set_error_handler() 捕獲 eval() 中的解析錯(cuò)誤。
范例
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.
注釋
Note: 因?yàn)槭且粋€(gè)語言構(gòu)造器而不是一個(gè)函數(shù),不能被 可變函數(shù) 調(diào)用。
Tip和直接將結(jié)果輸出到瀏覽器一樣,可使用輸出控制函數(shù)來捕獲當(dāng)前函數(shù)的輸出,然后(例如)保存到一個(gè) string 中。
Note:
如果在執(zhí)行的代碼中產(chǎn)生了一個(gè)致命的錯(cuò)誤(fatal error),整個(gè)腳本會退出。
參見
call_user_func() - 把第一個(gè)參數(shù)作為回調(diào)函數(shù)調(diào)用