Summary of php eval function usage

  • 2020-05-26 07:57:57
  • OfStack

Definition and usage of eval

The eval() function evaluates the string as PHP code.

The string must be valid PHP code and must end with a semicolon.

If the return statement is not called in the code string, NULL is returned. If there is a parsing error in the code, the eval() function returns false.

grammar
eval(phpcode)

Parameters to describe
phpcode required. Specifies the PHP code to calculate.

Hints and comments
Comment: the return statement immediately terminates the evaluation of the string.
Note: this function is useful for storing code in a database text field for later computation.
example

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

Output:
Copy the code as follows: This is a $string $time morning!
This is a beautiful winter morning!
The eval() function is also available in the CodeIgniter framework. In/system database/DB php file, according to the configuration of system dynamic CI_DB defines a class, specific code snippet below:?
 
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); 


This function replaces the value of a variable in a string and is usually used to process data from a database. The parameter code_str is the string to be processed. It is important to note that the string to be processed should conform to PHP's string format, with a semicolon at the end. The string processed using this function continues to the end of the PHP program.


Related articles: