Definition and usage
The eval () function calculates the string according to the PHP code.
The string must be a valid PHP code and must end with a semicolon.
If no return statement is called in the code string, NULL is returned. If there is a parsing error in the code, the eval () function returns FALSE.
Grammar
Parameters |
Description |
Phpcode |
Necessary. Specifies the PHP code to be computed. |
Hints and Notes
Note: The return statement terminates the calculation of the string immediately.
Note: This function is useful for code storage that is made available for future calculations in a database text field.
Example
<?php
$string
=
"beautiful"
;
$time
=
"winter"
;
$str
=
‘This is a $string $time morning!‘
;
echo
$str
.
"<br />"
;
eval
(
"\$str = \"$str\";"
);
echo
$str
;
?>
|
Output:
This is a $string $time morning! This is a beautiful winter morning!
The eval () function is also useful in the CodeIgniter framework. In the/system/database/db.php file, a class ci_db is dynamically defined according to the configuration of the system, with the following code snippet:
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
);
|
PHP eval () function