Alternative for 'eval() uating' a

2019-05-23 08:12发布

In the legacy codebase that I am working on, there is a condition evaluator which accepts user input to build a condition. This condition is then evaluated at run-time using php eval(). What is the best way to resolve this without using eval.

For e.g. I have a condition "1>0" entered by the user in the UI. This has to evaluated and the result (true in this case) returned. Any suggestions?

Let know if the problem seems vague, I would try and explain better.

标签: php eval
2条回答
聊天终结者
2楼-- · 2019-05-23 08:45

I'd say the pattern most suited for this would be the Specification pattern.

In computer programming, the specification pattern is a particular software design pattern, whereby business logic can be recombined by chaining the business logic together using boolean logic.

However, that approach would require you to write a parser for the input given by your users to safely transform the conditions to the specification instances. Depending on the complexity of conditions allowed, this might not be an easy task.

You could achieve the same by creating lambda functions with create_function for the assertions, but that is as insecure as using eval when it comes to user input.

查看更多
何必那么认真
3楼-- · 2019-05-23 08:52

The evalMath parser over on PHPClasses provides a safe framework for evaluating this type of expression.

查看更多
登录 后发表回答