PHP 函数参数错误抑制、empty() isset() 模拟
我很确定这个问题的答案是否定的,但是如果有一些 PHP 大师,
是否可以编写一个函数,以便可以传入无效参数或不存在的变量,并且 php 在不使用的情况下不会出错'@'
很像empty 和isset 的作用。 你可以传入你刚刚编写的变量,不会出错。
ex:
empty($someBogusVar); // no error
myHappyFunction($someBogusVar); // Php warning / notice
I'm pretty sure the answer to this question is no, but in case there's some PHP guru
is it possible to write a function in a way where invalid arguments or non existent variables can be passed in and php will not error without the use of '@'
Much like empty and isset do. You can pass in a variable you just made up and it won't error.
ex:
empty($someBogusVar); // no error
myHappyFunction($someBogusVar); // Php warning / notice
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(14)
当变量通过引用传递时,您不会收到任何错误(PHP 将默默地创建一个新变量):
但我建议不要滥用它来隐藏编程错误。
You don't get any error when a variable is passed by reference (PHP will create a new variable silently):
But I recommend against abusing this for hiding programming errors.
总而言之,正确的答案是不,你不应该(请参阅下面的警告)。
此线程中的许多人已经提到了一些解决方法,例如在条件中使用引用变量或 isset() 或 empty() 以及在 PHP 配置中抑制通知。 除了明显的解决方法之外,使用@,这是您不想要的。
总结与 Gerry 的有趣评论讨论:如果您检查以下值,则通过引用传递变量确实有效函数内的变量并正确处理未定义或 null 情况。 只是不要使用引用传递作为关闭 PHP 的一种方式(这是我的原文不应该指出的地方)。
Summing up, the proper answer is no, you shouldn't (see caveat below).
There are workarounds already mentioned by many people in this thread, like using reference variables or isset() or empty() in conditions and suppressing notices in PHP configuration. That in addition to the obvious workaround, using @, which you don't want.
Summarizing an interesting comment discussion with Gerry: Passing the variable by reference is indeed valid if you check for the value of the variable inside the function and handle undefined or null cases properly. Just don't use reference passing as a way of shutting PHP up (this is where my original shouldn't points to).
您可以使用 func_get_args 来执行此操作,如下所示:
此 func 更进一步,将为您提供任意数量的参数的第一个非空值(您始终可以强制它只接受最多两个参数,但这对我来说看起来更有用,例如这)。
编辑:原始版本没有使用紧凑来尝试创建参数数组,并且仍然给出错误。 错误报告提高了一个档次,这个带有紧凑的新版本有点不太整洁,但仍然做同样的事情,并允许您为不存在的变量提供默认值。
You can do this using func_get_args like so:
This func goes one step further and would give you the first non empty value of any number of args (you could always force it to only take up to two args but this look more useful to me like this).
EDIT: original version didn't use compact to try and make an array of args and STILL gave an error. Error reporting bumped up a notch and this new version with compact is a little less tidy, but still does the same thing and allows you to provide a default value for non existent vars.
我确信关于三元运算符 vrs 函数调用可能会有很好的讨论。 但这个问题的重点是看看我们是否可以创建一个函数,如果在不使用“@”的情况下传入不存在的值,则该函数不会抛出错误
I'm sure there could be a great discussion on ternary operators vrs function calls. But the point of this question was to see if we can create a function that won't throw an error if a non existent value is passed in without using the '@'
这返回 $value 或 $default。 取决于 $value 的值。 如果它是 0、false、空或任何类似的值,则将返回 $default 中的值。
我更愿意接受模拟empty()和isset()等函数的挑战
this returns either $value OR $default. Depending upon the value of $value. If it is 0, false, empty or anything similar the value in $default will be returned.
I'm more going for the challenge to emulate functions like empty() and isset()
@Sean 布莱恩已经回答了
@Sean That was already answered by Brian
肖恩,你可以这样做:
编辑:
我告诉过你,用
isset()
检查它。 三元条件的第一部分不检查 null 或非 null,而是检查true
或false
。 如果您尝试在 PHP 中检查 null 值的true
或false
,您会收到这些警告。 isset() 检查变量或表达式是否返回空值,并返回一个布尔值,该布尔值可以由三元组的第一部分进行评估,不会出现任何错误。Sean, you could do:
EDIT:
And I told you, check it with
isset()
. A ternary conditional's first part doesn't check null or not null, it checkstrue
orfalse
. If you try to checktrue
orfalse
on a null value in PHP, you get these warnings.isset()
checks whether a variable or expression returns a null value or not, and it returns a boolean, which can be evaluated by the first part of your ternary without any errors.在某些情况下,检查会变得麻烦且不必要。
因此,我编写了这个小神奇函数:
它不需要对 myHappyFunction() 进行任何更改。
您必须更改
为
明确陈述您的意图。 这使得它成为我书中的良好实践。
There are valid cases where checking becomes cumbersome and unnessesary.
Therfore i've written this little magic function:
It doesn't require any changes to myHappyFunction().
You'll have to change
to
Stating your intent explicitly. which makes it good practice in my book.
不,因为这实际上与该功能无关; 该错误来自于尝试取消引用不存在的数组键。 您可以更改 PHP 设置的警告级别来抑制这些错误,但最好不要这样做。
话虽如此,您可以做类似的事情
并使用它代替数组键查找
现在我需要洗澡:)
No, because this isn't really anything to do with the function; the error is coming from attempting to de-reference a non-existent array key. You can change the warning level of your PHP setup to surpress these errors, but you're better off just not doing this.
Having said that, you could do something like
And use it in place of array key lookup
Now I need to take a shower :)
是的,可以!
porneL 是正确的[编辑:我没有足够的点来链接到他的答案或投票,但它在这个页面上]
当他警告“但我建议不要滥用它来隐藏编程错误”时,他也是正确的。 然而,出于同样的原因,也应该避免通过错误控制运算符 (@) 进行错误抑制。
我是 Stack Overflow 的新手,但我希望错误答案在页面上排名最高而正确答案没有获得投票的情况并不常见。 :(
Yes you can!
porneL is correct [edit:I don't have enough points to link to his answer or vote it up, but it's on this page]
He is also correct when he cautions "But I recommend against abusing this for hiding programming errors." however error suppression via the Error Control Operator (@) should also be avoided for this same reason.
I'm new to Stack Overflow, but I hope it's not common for an incorrect answer to be ranked the highest on a page while the correct answer receives no votes. :(
虽然最初问题的答案是“否”,但还有一个没有人提到的选项。
当您使用 @ 符号时,PHP 所做的就是覆盖
error_reporting
级别并将其暂时设置为零。 您可以使用“ini_restore('error_reporting');
”将其设置回使用@之前的状态。当我想编写一个方便的函数来检查变量是否已设置并且还有一些其他属性时,这对我很有用,否则返回默认值。 但是,发送未设置的变量会导致 PHP 通知,因此我使用 @ 来抑制该通知,然后将
error_reporting
设置回函数内的原始值。例如:
因此,在上面的情况下,如果未设置
$bar
,当我使用不存在的变量调用foo()
时,我不会收到错误。 但是,我会在函数内收到错误,错误地输入了is_set
而不是isset
。这可能是一个有用的选项,涵盖了最初问题在精神上(如果不是实际上)所问的问题。
While the answer to the original question is "no", there is an options no one has mentioned.
When you use the @ sign, all PHP is doing is overriding the
error_reporting
level and temporarily setting it to zero. You can use "ini_restore('error_reporting');
" to set it back to whatever it was before the @ was used.This was useful to me in the situation where I wanted to write a convenience function to check and see if a variable was set, and had some other properties as well, otherwise, return a default value. But, sending an unset variable through caused a PHP notice, so I used the @ to suppress that, but then set
error_reporting
back to the original value inside the function.Something like:
So, in the case above, if
$bar
is not set, I won't get an error when I callfoo()
with a non-existent variable. However, I will get an error from within the function where I mistakenly typedis_set
instead ofisset
.This could be a useful option covering what the original question was asking in spirit, if not in actual fact.
如果只是给参数添加一个默认值,那么在调用函数时就可以跳过它。 例如:
If you simply add a default value to the parameter, you can skip it when calling the function. For example:
只需一行,您就可以完成它:
myHappyFunction($someBogusVar="");
我希望这就是您正在寻找的。 如果您阅读 php 文档,在默认参数值下,您可以看到分配函数参数的默认值可以帮助您在使用函数时防止出现错误消息。
在此示例中,您可以看到使用默认参数的区别及其优点:
PHP 代码:
test1()
行的输出:test2()
行的输出:这也可以与 isset() 和其他函数结合使用来完成您想要的任务。
With a single line, you can acomplish it:
myHappyFunction($someBogusVar="");
I hope this is what you are looking for. If you read the php documentation, under default argument values, you can see that assigning a default value to an function's argument helps you prevent an error message when using functions.
In this example you can see the difference of using a default argument and it's advantages:
PHP code:
Output for
test1()
lines:Output for
test2()
lines:This can also be used in combination to
isset()
and other functions to accomplish what you want.再往上看抽象树,你用这个做什么?
您可以根据需要初始化每个类中的这些值,也可以创建一个包含所有默认值和属性的特定类,例如:
这个想法是,当在代码中到处使用 defaultValue 函数时,无论何时,它都会成为维护噩梦您必须更改值,查找所有调用 defaultValue 的位置。 而且它也可能会导致您重复自己,违反 DRY。
而这是存储所有这些默认值的单个位置。 您可能会想避免创建这些 setter 和 getter,但它们也有助于维护,以防需要对输出进行一些修改或验证输入。
And going further up the abstraction tree, what are you using this for?
You could either initialize those values in each class as appropriate or create a specific class containing all the default values and attributes, like:
The idea being that, when using defaultValue function everywhere up and down in your code, it will become a maintenance nightmare whenever you have to change a value, looking for all the places where you've put a defaultValue call. And it'll also probably lead you to repeat yourself, violating DRY.
Whereas this is a single place to store all those default values. You might be tempted to avoid creating those setters and getters, but they also help in maintenance, in case it becomse pertinent to do some modification of outputs or validation of inputs.