简体   繁体   中英

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.

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.

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:'.

建议您不要对PHP的错误处理进行修改,而是建议对脚本施加一些约束,并使用PHP的issetemptyis_null函数检查变量。

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.

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