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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With