PHP eval() 函數

PHP Misc 參考手冊 PHP Misc 參考手冊

實例

把字串當成 PHP 代碼來計算:

<?php $string = "beautiful"; $time = "winter"; $str = 'This is a $string $time morning!'; echo $str. PHP_EOL; eval("\$str = \"$str\";"); echo $str; ?>

以上代碼執行輸出結果為:

This is a $string $time morning!
This is a beautiful winter morning!


定義和用法

eval() 函數把字串按照 PHP 代碼來計算。

該字串必須是合法的 PHP 代碼,且必須以分號結尾。

注釋:return 語句會立即終止對字串的計算。

提示:該函數對於在資料庫文本字段中供日後計算而進行的代碼存儲很有用。


語法

eval(phpcode)

參數 描述
phpcode 必需。規定要計算的 PHP 代碼。

技術細節

返回值: 除非在代碼字串中調用 return 語句,則返回傳給 return 語句的值,否則返回 NULL。如果代碼字串中存在解析錯誤,則 eval() 函數返回 FALSE。
PHP 版本: 4+


PHP Misc 參考手冊 PHP Misc 參考手冊