代码之家  ›  专栏  ›  技术社区  ›  Armen Michaeli

有什么方法可以让php在未设置/未定义的变量和数组索引等上中止?

  •  0
  • Armen Michaeli  · 技术社区  · 14 年前

    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).

    有没有人有一个整洁和非黑客的解决方案?有什么推荐的方法吗?

    干杯。

    4 回复  |  直到 14 年前
        1
  •  3
  •   Pekka    14 年前

    我相信没有本地的PHP方法可以做到这一点。

    扩展已经存在的错误处理程序以查找错误消息( stristr($errmsg, "undefined variable") ... ) die() 如果必要的话,这是最好的(也是唯一的)方法。

        2
  •  3
  •   Lukman    14 年前

    您可以使用php函数 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:'.

        3
  •  2
  •   mmattax    14 年前

    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 is_null 功能。

        4
  •  0
  •   Artefacto    14 年前

    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.