Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/243.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中,如何包装我自己的is_空函数?_Php - Fatal编程技术网

在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()
,不幸的是,您不能。当您将值传递到方法中时,您已经触发了通知。这将在返回变量值的同时设置变量。也就是说,如果未设置变量,则将设置变量。是的,我应该记得使用参考资料。非常感谢你。