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?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
Bad application design is always such an example.
Using eval is quite dangerous, if see from security side. Anyway, a lot of template engines use eval, because they should parse page and get some variables or make calculations.
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
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.
Well I have used eval once. This was for a system, where the users could enter formulas using constants fished from the underlying system.
A string like:
was taken and the constants replaced with values from the system eval is then used to get a value. eval seemed like the easiest way to go. The statement was filtered to only allow operators and uppercase letters(no two next to each other) so perhaps this is not a "real" use case of eval, but it works and is pretty readable.
That said the system in questing is huge (200k+ lines) and this is the only place that eval is used.
Eval useful for example in such case, as register widgets in cycle in wordpress while creating custom theme:
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.