Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about eval in PHP 5

Tags:

php

eval

I have been doing PHP stuff for almost one year and I have never used the function eval() though I know the usage of it. But I found many questions about it in SO.So can someone show me a simple example in which it's necessary to use eval()?And is it a good or bad practice?

like image 382
Young Avatar asked Mar 11 '26 04:03

Young


2 Answers

eval() is necessary to implement a "compiling" template engine, like Smarty, that uses its own language and compiles it down to php on the fly. The main function of such engines is usually something like

 function render_template($path) {
    $code = file_get_contents($path);
    $php = $this->compile_to_php($code);
    eval($php);
 }

Besides that, everytime you use "include" or "require", you're actually using "eval" under the hood - so, actually, eval is one of the mostly used php constructs.

like image 79
user187291 Avatar answered Mar 12 '26 18:03

user187291


Using eval() is a bad practice, and if it turns out to be necessary to achieve something, that is usually the sign of a underlying design error.

I can't think of any situation where it is necessary to use eval(). (i.e. something can't be achieved using other language constructs, or by fixing a broken design.) Interested to see whether any genuine cases come up here where eval actually is necessary or the alternative would be horribly complex.

The only instance of where it could be necessary is for executing code coming from an external source (e.g. database records.) But this is a design error in itself IMO.

like image 41
Pekka Avatar answered Mar 12 '26 18:03

Pekka