简体   繁体   中英

Catching certain errors with PHP eval()

UPDATE: I realize that there are flaws with eval(), but I'm "supposed" to use it for this particular problem. So any solution to the issue needs to keep this in mind.

I'm just getting started with PHP in a class of mine and am implementing a very limited calculator using regular expressions (with preg_match(), to be specific) and eval(). One of the features of the calculator is that when it's given any form of bad input, a simple error message written by me is displayed rather than the default PHP errors. This works for most bad inputs (strings with letters, multiple operators in a row, etc.), but I have been unable to catch other kinds of errors. In particular, the inputs:

0/0

and things like

2--1

The latter expression is technically well formed, but I'm not required to handle it (presumably to keep our code simpler as this is a simple project to get us acquainted with PHP) and can instead output my simple error message as a response. The calculator doesn't support parentheses, so an expression like

2-(-1)

would be invalid. The trouble is that I can't seem to figure out what eval() is returning upon encountering things like this, if it's even returning at all.

Does eval() always return? I've read the eval() documentation a few times but still can't seem to figure out what sort of things I should check for. I'd rather have an explanation of what to check for and why rather than simply blindly checking return values and their complements until I figure it out. Below are screenshots of the two errors described above (I don't have enough reputation to embed them here). Any help would be appreciated!

Division by zero error

Multiple operator error

This may seem like a harsh thing to say, but don't do that! Don't use eval() like that, it's dangerous. Asides from it being a much safer way to do things, you'll learn much more by writing a simple tokeniser to break the input into your calculator up, and then use Dijkstra's Shunting Yard algorithm to (a) turn it into something that can be evaluated by a stack machine and to (b) identify unexpected tokens in your token stream (such as operators where you expect digits).

eval() is not guaranteed to run because you're not just evaluating simple expressions, but arbitrary code.

If you absolutely have to use eval() , use set_error_handler() and the @ error suppression operator to intercept errors before they get spat out at the user. You can use the error_reporting() function to tell if the error captured was suppressed using @ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM