Armen Michaeli
Armen Michaeli

Reputation: 9140

Any way to make PHP abort on unset/undefined variables and array indexes and such?

Currently, PHP would trigger (and log if logging is enabled) E_NOTICE 'errors' when accessing undefined variables and array indexes. Is there a way to make it abort on these, so that I know I don't miss any. Frankly, IMO, far too often a script SHOULD abort on such condition anyway, as it will inevitably break something farther down the execution path. In all other cases there is the '@' operator, that's what it is for, right?

I know I can use a custom error handler and abort on any condition. In fact I do use one already, but I do have places where I trigger notices myself (granted, E_USER_NOTICE instead of PHP's own E_NOTICE), and I also always return false letting PHP's own internal handler do its job - logging and aborting on errors, continuing on everything else.

Then there are other cases where PHP produces E_NOTICE without me wanting to abort the script. Basically, there is no way for me to know if a particular E_NOTICE is a result of an unset variable or a totally harmless condition (which notices should be caused by anyway).

Has anyone a neat and non-hackish solution? Some recommended way of doing this?

Cheers.

Upvotes: 0

Views: 827

Answers (4)

Artefacto
Artefacto

Reputation: 97835

I'm not sure what you want. You want to abort on notices, but not every notice? You want to distinguish between the several types of E_NOTICES and abort on some? The only way to do this is to check the message in the error handler and not abort if the message is about undefined variables – which you shouldn't use, by the way.

Upvotes: 0

Lukman
Lukman

Reputation: 19164

You can user PHP function set_error_handler() to register a custom function that will handles any PHP error. Specify E_NOTICE as the second parameter so that your custom function will only receive E_NOTICE error. Then in that function, simply do 'exit;' if the second parameter which is the error message starts with 'Undefined offset:'.

Upvotes: 3

mmattax
mmattax

Reputation: 27670

Rather than try to hack around PHP's error handling, I suggest you enforce some constraints on your script and check your variables with PHP's isset, empty and is_null functions.

Upvotes: 2

Pekka
Pekka

Reputation: 449475

I'm sure there is no native PHP way to do this.

Extending your already existent error handler to look into the error message (stristr($errmsg, "undefined variable") ...) and die() if necessary is the best (and only) way that comes to mind.

Upvotes: 3

Related Questions