Home > Backend Development > PHP Tutorial > Introduction and usage examples of PHP function eval(), eval example_PHP tutorial

Introduction and usage examples of PHP function eval(), eval example_PHP tutorial

WBOY
Release: 2016-07-13 10:20:30
Original
1216 people have browsed it

Introduction and usage examples of PHP function eval(), eval examples

What is eval()?

The eval() function evaluates strings according to PHP code.
The string must be valid 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)

Copy code The code is as follows:

Parameter Description
phpcode required. Specifies the PHP code to be calculated.

Example 1

Copy code The code is as follows:

$string = "beautiful";
$time = "winter";

$str = 'This is a $string $time morning!';
echo $str. "
";

eval("$str = "$str";");
echo $str;
?>

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

Example 2

We use a for loop to create n random numbers, and the values ​​​​are doubled

Copy code The code is as follows:


for($i=1;$i<=10;$i++){
         eval('$a'.$i.'='.($i*$i).';');
}

for($i=1;$i<=10;$i++){
          eval('echo $a'.$i.'.'
' ;');
}

echo '
';
echo $a1 + $a10;

Output:
Copy code The code is as follows:

1
4
9
16
25
36
49
64
81
100
101

How to use the eval() function in PHP

eval() must be a string in brackets

If you write $a=1; eval("echo (\$a+\$b);"); the running result is 1

If $a=1; eval("echo ($a+$b);"); then an error will be reported

This means that it is best to have a strict string and a complete PHP statement

$a=1; eval("echo \$a;");
$a=1; eval("echo $a;");
The above result is the same as the first eval is executed echo $a; and the second sentence executes echo 1;

How does PHP use the eval() function to change this instance?

$f ='$';

$f.$a.$this->i
What is the way to write this? Obviously it is not the effect you want. This is equivalent to a string Connected. Probably what you mean is this, $($a.$this->i). Let’s think about the other things slowly

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/866677.htmlTechArticlePHP function eval() introduction and usage examples, eval examples What is eval() The eval() function converts a string Calculated according to PHP code. The string must be valid PHP code and must be preceded by a semicolon...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template