eval() is a language construct in PHP, which is used to evaluate a given string as PHP code and then execute it. In this tutorial, you will learn about the usage and benefits of PHP eval().
Usage of PHP eval()
The eval() is meant for evaluating a PHP string as a PHP code. The string that will be passed as a parameter within the eval() has to be a valid PHP code along with a semicolon ending it (all within that function itself). Furthermore, the parameter string should not hold any of PHP's opening or closing tags associated with it.
PHP eval is very useful in cases where the code can be stored in the database and execute later.
Syntax:
eval( $string )
This function will accept a single string parameter. All statements within it must be properly terminated with a semicolon. For example, if you mention it like this:
'echo "Hello World!"', It will give you a parsing error message. So, in order to correctly execute the string within eval(), you have to initialize it as 'echo "Hello World!";'. Moreover, this function will return a NULL if the programmer does not call any return statement; otherwise, it will return a value. Another reason when the function will return FALSE is if there is a parsed error in the input string.
Here is a PHP program showing the use of eval():
Example:
<?php
$mySal = 40000;
$strg = 'The given Salary is $mySal';
echo $strg. "\n";
eval("\$strg = \"$strg\";");
echo $strg. "\n";
?>
Program Output:
The given Salary is $mySal The given Salary is 40000
Another PHP code snippet showing the use of it within a single statement:
Example:
<?php
echo eval('echo "Hello world, I am a PHP script!";');
?>
Program Output:
Hello world, I am a PHP script!