This article introduces several examples of the eval function in PHP. Friends in need can refer to it.
In php, the eval function is used to substitute values into strings. Syntax: void eval(string code_str); Return value: None Function type: Data processing Content description This function can substitute the variable value in the string and is usually used to process database data. The parameter code_str is the string to be processed. Note: The string to be processed must conform to PHP's string format and must have a semicolon at the end. The string processed using this function will continue until the end of the PHP program. Example: <?php $string = '杯子'; $name = '咖啡'; $str = '这个 $string 中装有 $name.<br>'; echo $str; eval( "/$str = /"$str/";" ); echo $str; ?> Copy after login The return value is: This $string contains $name. This cup contains coffee. Attached, the definition and usage of eval. Theeval() function evaluates strings according to PHP code. The string must be legal PHP code and must end with a semicolon. If no return statement is called in the code string, NULL is returned. If there are parsing errors in the code, the eval() function returns false. Grammar eval(phpcode) Parameter Description phpcode required. Specifies the PHP code to be calculated. Tips and Notes Note: The return statement immediately terminates evaluation of the string. Note: This function is useful for storing code in a database text field for later calculation. Example: <?php $string = "beautiful"; $time = "winter"; $str = 'This is a $string $time morning!'; echo $str. "<br />"; eval("$str = "$str";"); echo $str; ?> Copy after login Output: This is a $string $time morning! This is a beautiful morning winter! Theeval() function is also used in the CodeIgniter framework. In the /system/database/DB.php file, a class CI_DB is dynamically defined based on the system configuration. Example: <?php if ( ! isset($active_record) OR $active_record == TRUE) { require_once(BASEPATH.'database/DB_active_rec.php'); if ( ! class_exists('CI_DB')) { eval('class CI_DB extends CI_DB_active_record { }'); } } else { if ( ! class_exists('CI_DB')) { eval('class CI_DB extends CI_DB_driver { }'); } } require_once(BASEPATH.'database/drivers/'.$params['dbdriver'].'/'.$params['dbdriver'].'_driver.php'); // Instantiate the DB adapter $driver = 'CI_DB_'.$params['dbdriver'].'_driver'; $DB = new $driver($params); Copy after login The above code can substitute the variable value in the string and is usually used to process database data. The parameter code_str is the string to be processed. Note that the string to be processed must conform to PHP's string format and must have a semicolon at the end. The string processed using this function will continue until the end of the PHP program. |