PHP function eval () introduction and use example _ php instance

Source: Internet
Author: User
This article mainly introduces the eval () function of PHP and the example of its use. This article provides a special example, which is to use eval nested for execution in a loop. For more information, see What is eval ()?

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 the return statement is not called in the code string, NULL is returned. If a parsing error exists in the code, the eval () function returns false.

Syntax

Eval (phpcode)

The code is as follows:


Parameter description
Phpcode is required. Specifies the PHP code to be calculated.

Example 1

The code is as follows:


<? Php
$ 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 winter morning!

Example 2

We use the for loop to create n random values, and the values increase exponentially.

The code is as follows:


<? Php

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:

The code is as follows:


1
4
9
16
25
36
49
64
81
100
101

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.