在PHP中,如何包装我自己的is_空函数?
我尝试使用在PHP中,如何包装我自己的is_空函数?,php,Php,我尝试使用empty()包装自己的函数。 名为的函数是空的用于检查值是否为空,如果为空,则返回指定的值。代码如下 static public function is_empty($val,$IfEmptyThenReturnValue) { if(empty($val)) { return $IfEmptyThenReturnValue; } else { re
empty()
包装自己的函数。
名为的函数是空的
用于检查值是否为空,如果为空,则返回指定的值。代码如下
static public function is_empty($val,$IfEmptyThenReturnValue)
{
if(empty($val))
{
return $IfEmptyThenReturnValue;
}
else
{
return $val;
}
}
我这样称呼这个函数:
$d="it's a value";
echo Common::is_empty($d, "null");
没关系。它打印了“这是一种价值”
但是如果我没有定义$d
。如下图所示:
echo Common::is_empty($d, "null");
是的,它将打印“空”。
但它也会打印一个警告:注意
:
Undefined variable: d in D:\phpwwwroot\test1.php on line 25.
那么如何修复此函数呢?您可以通过输入变量名称而不是变量本身来解决此问题,然后在函数中使用变量变量:
static public function is_empty($var, $IfEmptyThenReturnValue)
{
if(empty($$var))
{
return $IfEmptyThenReturnValue;
}
else
{
return $$var;
}
}
echo Common::is_empty('d', 'null');
然而,首先,我要做的是,为这一点提供一个函数:
echo empty($d) ? 'null' : $d;
一个简单的
和来拯救你的生命:
class Common{
static public function is_empty(&$val,$IfEmptyThenReturnValue){
if(empty($val)){
return $IfEmptyThenReturnValue;
}else{
return $val;
}
}
}
echo Common::is_empty($d,"null");
在函数中使用isset()
,不幸的是,您不能。当您将值传递到方法中时,您已经触发了通知。这将在返回变量值的同时设置变量。也就是说,如果未设置变量,则将设置变量。是的,我应该记得使用参考资料。非常感谢你。