I use eval()
in my current project like this:
if (class_exists($class_name)) //$class_name depends on user input
eval($class_name.'::MyStaticMethod()');
eval()
is executed if and only if class with the name $class_name
exists so it's kinda safe, but I still don't think that this is the best solution.
Can I do the same what code above does without eval()
?
I'd suggest
call_user_func
.An alternative to
call_user_func()
would be calling it like this:As of PHP 5.3+,
yes:
Adisory: userinput + eval = security hole;
Also eval is an expensive operation requiring parsing the string into an actionable format (parse tree, abstract syntax tree, etc.) and executing the new found logic.
You don't want to eval every little tidbit of code. Use eval if you have something for it to chew on or rather put that logic somewhere where it's reusable and parametrized such as a function.
Also as of php 5.4
I have recently answered this question. The last part of my answer perfectly answers this question and is much more useful for future readers than answers provided here. That's why I am answering my own question.
PHP has features that gives possibility to avoid using
eval
in most cases:PHP is very dynamic language. It has ability to do following stuff with
strings
:Define and/or get variable (supported from PHP 4.3). For example:
Demo
Call function (supported from PHP 4.3). For example:
Demo
Create instance of class (supported from PHP 5.0). For example:
Demo
Call static method (supported from PHP 5.0). For example:
Demo
And from PHP 5.3 class name can also be defined by string. Example:
Demo
Call instance method of object (supported from PHP 5.0). For example:
Demo
Access static and instance properties of object (supported from PHP 5.0). For example:
Demo
call_user_func
andcall_user_func_array
for dynamic function/method calls. Both are perfectly documented so I won't go in details here.Reflection
API. Unfortunately, documentation has few examples but reflection is quite large topic to cover here. Basically, It's not a big deal to use reflection after reading how it works.