简体   繁体   English

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

[英]Custom function to check if variables in array are set

What I'm trying to do is write one function to reuse vs writing out an if statement every time. 我想做的是编写一个函数以重用,而不是每次都编写一个if语句。

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. 函数有效,但是我仍然收到“ undefined”错误消息,这是我要避免的错误消息。

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;
}

The problem in your code is, that you still pass an undefined variable to your function, so that's why you still get your undefined error. 代码中的问题是,您仍然将未定义的变量传递给函数,因此这就是为什么仍会收到未定义的错误的原因。

One way to solve this now, is that you pass your variable name as a string and then use variable variables , to check if it exists, eg 现在解决此问题的一种方法是,将变量名作为字符串传递,然后使用变量variable来检查其是否存在,例如

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

echo'name'.isSetTest("value");

Demo 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM