duanfu3390 2015-06-24 14:07
浏览 32
已采纳

用于检查数组中的变量是否已设置的自定义函数

What I'm trying to do is write one function to reuse vs writing out an if statement every time.

If statement:

if (!isset($value)){ echo 'null';}else{ echo $value;}

Function:

function isSetTest($value){
    if ( !isset($value)){
       $value = NULL;
    }
    return $value;
}

echo'name'.isSetTest($value);

Function works but I still get the "undefined" error message which is what i'm trying to avoid.

  • 写回答

2条回答 默认 最新

  • dragon7713 2015-06-24 14:18
    关注

    Pass by reference instead, so that no processing of the variable is done until you want it:

    function isSetTest(&$value) { // note the &
        if (!isset($value)) {
           $value = NULL;
        }
        return $value;
    }
    

    You can shorten this a bit:

    function isSetTest(&$value) {
        return isset($value) ? $value : null;
    }
    

    I have a function that does something similar, except you can provide an optional default value in the case that the variable is not set:

    function isset_or(&$value, $default = null) {
        return isset($value) ? $value : $default;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部