Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
communitycreator

What is the eval() method in PHP?

NDUKWE CHIDERA K.

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The PHP built-in eval() method is used to parse a string as PHP code.

This function can be used in situations where there is no option to evaluate such strings.

If there is no other option and you have to use this function, do ensure that there is no user-specified string being passed, as it can contain dangerous scripts.

Syntax

eval($code);

Parameters

  • $code: This specifies the valid PHP code to be evaluated by the function and is of the string type. It is the only parameter of this method.

Code string specifics

The code should not be wrapped in opening and closing PHP tags.

For example, 'echo "Hello!";' should be passed to the function rather than '<?php echo "Hello!"; ?>'.

It is still possible to leave and re-enter PHP mode using the appropriate PHP tags.

For example:

echo "In PHP mode!"; ?>In HTML mode!<?php echo "Back in PHP mode!";

Ensure that the PHP code is a valid one. This simply entails that all statements must be properly terminated using a semicolon.

For example, echo "Hello!" will cause a parse error, whereas echo "Hello!"; will work.

The code will be executed in the scope of the code calling eval(). Thus, any variables defined or changed in the eval() call will remain visible after it terminates.

Return value

The eval() method returns null unless a return statement is called in the code string. In this case, the value passed to return is returned.

In case there is a parse error in the code string, the method returns false.

Code


<?php
$string = 'stone';
$name = 'rock';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$string = \"$str\";");
echo $string. "\n";
?>

Explanation

In the code above, the $string variable and the $name variable were evaluated by the eval() function in line 8.

RELATED TAGS

php
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring