如何在PHP中创建一个取消指定变量的函数
问题描述:
I'm trying to make a function that takes a variable whether it was set or not,
like the function isset()
//we have this array
$array = array();
isset($array["test"]);//this one is valid
myFunc($array["test"]);//this one is not valid
how can i let my function take not set variables?
我正在尝试创建一个带变量的函数,无论它是否已设置, p> \ n
就像函数isset() p>
//我们有这个数组
$ array = array();
isset($ array [“test” ]); //这个有效
myFunc($ array [“test”]); //这个无效
code> pre>
我怎么能让我的 函数取不设置变量? p>
div>
答
Pass the argument as a reference http://php.net/manual/en/language.references.pass.php
function myFunc(&$val)
{
return isset($val);
}
var_dump(myFunc($undefined));
答
It's common to come across this problem if you're using $_GET
and friends, because you can't rely on a given field being passed into your program.
I use a utility class for this, so I can avoid errors with unset vars and also populate defaults into them.
<?php
function defArrayElem(&$array, $key, $default=null) {
if(!isset($array[$key])) {$array[$key]=$default;}
}
//repeat for all the $_GET/$_POST vars you expect...
defArrayElem($_GET,'keyname','default-value');
?>
Now you don't need to worry about checking if they're set or not.