用于检查数组中的变量是否已设置的自定义函数
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.
我要做的是编写一个函数来重用,每次写出一个if语句。 p>
if语句: p>
if(!isset($ value)){echo'null';} else {echo $ value;} \ n code> pre>
功能: p>
function isSetTest($ value){
if(!isset($ value)) {
$ value = NULL;
}
返回$ value;
}
echo'name'.isSetTest($ value);
code> pre>
函数有效,但我仍然收到“未定义”错误消息,这是我试图避免的。 p>
div>
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, e.g.
function isSetTest($value){
global $$value;
if ( !isset($$value)){
$$value = NULL;
}
return $$value;
}
echo'name'.isSetTest("value");