PHP 抑制函数参数中的错误
来自 https://stackoverflow.com/a/55191/547210
的扩展 我正在创建一个验证函数来检查字符串变量的多个属性,这些属性可能已设置,也可能未设置。 (检查的属性之一)
我试图对该函数执行的操作是接收表单中未知数量的参数(见下文),并抑制可能因传递未设置的变量而导致的错误。
我使用 func_get_args()
接收诸如 validate([ mix $... ] )
之类的变量
上一篇文章提到可以通过引用传递,现在当变量像这样隐式传递时可以吗?
Extension from https://stackoverflow.com/a/55191/547210
I am creating a validating function to check several attributes of string variables, which may or may not have been set. (One of the attributes which is checked)
What I am trying to do with the function is receive arguments an unknown number of arguments in the form (See below), and suppress errors that may be caused by passing an unset variable.
I'm receiving the variables like validate([ mixed $... ] )
by using func_get_args()
The previous post mentioned that it was possible by passing by reference, now is this possible when the variables are passed implicitly like this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果传递的变量未在调用范围中设置,则 func_get_args() 返回的数组将在传递该变量的位置包含一个 NULL 值,并且将触发错误。这个错误不是在函数代码本身触发的,而是在函数调用时触发的。因此,无法从函数代码中抑制此错误。
考虑一下:
正如您所看到的,变量名
notSet
出现在错误中,告诉我们错误是在调用者的范围内触发的,而不是在被调用者的范围内。如果我们想解决这个错误,我们可以这样做:
...并用邪恶的
@
运算符作为变量名的前缀,但更好的解决方案是以不同的方式构建我们的代码,所以我们可以这样做我们自己检查:If you pass a variable that is not set in the calling scope, the array returned by
func_get_args()
will contain aNULL
value at the position where the variable was passed, and an error will be triggered. This error is not triggered in the function code itself, but in the function call. There is, therefore, nothing that can be done to suppress this error from within the code of the function.Consider this:
As you can see, the variable name
notSet
appears in the error, telling us that the error was triggered in the caller's scope, not that of the callee.If we want to counter the error, we could do this:
...and prefix the variable names with the evil
@
operator, but a better solution would be to structure our code differently, so we can do the checks ourselves: