通过可能不会被设置为函数的参数,而不会发出通知 [英] pass an argument that may not be set to a function, without throwing a notice

查看:80
本文介绍了通过可能不会被设置为函数的参数,而不会发出通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP具有 isset()函数,它接受一个变量,并告诉你它是否被设置。它在传递不存在的数组键时不会发出通知。我想在一个新的函数中复制这个功能,如下所示:

  function my_function($ arg1,$ arg2 ){
if(isset($ arg1)){
//...do something
} else {
//...do else else
}
}

或者最终如下所示:

  function my_function(){
$ arglist = func_get_args();
foreach($ arglist as $ arg){
if(isset($ arg)){
// ...做某事
}
}
}

显然,这些功能不起作用。我可以使用@来抑制所有错误,然后只是测试null,但我宁愿留下错误报告。



有什么想法?

解决方案

所以,在广泛的鬼混之后,根据给出的答案,我找到了解决方案!

问题是范围之一,并且在赋值时发生错误检查,当您使用值调用函数时。



strong>



如果您通过引用传递变量,则不会触发错误检查!事实上,这些引用被传递,错误在第一次使用时被抛出,在函数内部!

  //返回第一个定义的非伪参数的HTML安全版本
函数print_OR(& $ highp = null,& $ lowp = null,& $ default = null){
if(isset($ highp)&&($ highp || $ highp === 0))return htmlspecialchars($ highp);
if(isset($ lowp)&&($ lowp || $ lowp === 0))return htmlspecialchars($ lowp);
return htmlspecialchars($ default);



$ b这些是一组测试, http://pastebin.com/C9QTvSi7 =nofollow> http://pastebin.com/C9QTvSi7


PHP has the isset() function, that takes a variable, and tells you whether it was set. It doesn't throw a notice when passed an array key that doesn't exist. I'd like to duplicate that functionality in a new function that does something like this:

function my_function($arg1, $arg2) {
    if(isset($arg1)) {
        //...do something
    } else {
        //...do something else
    }
}

or eventually something like this:

function my_function() {
    $arglist = func_get_args();
    foreach($arglist as $arg) {
        if(isset($arg)) {
            // ... do something
        }
    }
}

Obviously, these functions won't work. I could suppress all errors with @, and then just test for null, but I'd prefer to leave error reporting intact.

Any ideas?

解决方案

So, after extensive fooling around, based on the answers given, I found a solution!

The issue is one of scope, and the error-checking occurs at the moment of assignment, when you call a function with values.

HOWEVER

If you pass your variables by reference, error checking is not triggered! In fact, the references are passed, and errors are thrown at the first bad use, inside the function!

// returns an HTML-safe version of the first defined, non-falsey argument
function print_OR(&$highp = null, &$lowp = null, &$default=null) {
    if(isset($highp)&&($highp||$highp===0)) return htmlspecialchars($highp);
    if(isset($lowp )&&($lowp ||$lowp ===0)) return htmlspecialchars($lowp);
    return htmlspecialchars($default);
}

Here are a set of tests, showing this as functional: http://pastebin.com/C9QTvSi7

这篇关于通过可能不会被设置为函数的参数,而不会发出通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆