Question

I tried to wrap my own function using empty(). The function named is_empty is to check whether a value is empty, if it's empty, return a specified value. Code is as below.

static public function is_empty($val,$IfEmptyThenReturnValue)
    {
        if(empty($val))
        {
            return $IfEmptyThenReturnValue;
        }
        else
        {
            return $val;
        }
    } 

And I call this function like this:

$d="it's a value";
echo  Common::is_empty($d, "null");

That's ok. It printed the "it's a value".

but if I don't defined the $d. like below:

echo  Common::is_empty($d, "null");

Yes, it will print the "null". But it will also print a waring:Notice:

 Undefined variable: d in D:\phpwwwroot\test1.php on line 25.

So how to fix this function?

Était-ce utile?

La solution

A simple & to save your life:

class Common{
    static public function is_empty(&$val,$IfEmptyThenReturnValue){
        if(empty($val)){
            return $IfEmptyThenReturnValue;
        }else{
            return $val;
        }
    }
}

echo Common::is_empty($d,"null");

Autres conseils

You can get around this by passing in the name of the variable rather than the variable itself, and then utilising variable variables in the function:

static public function is_empty($var, $IfEmptyThenReturnValue)
{
    if(empty($$var))
    {
        return $IfEmptyThenReturnValue;
    }
    else
    {
        return $$var;
    }
} 

echo Common::is_empty('d', 'null');

However, instead having a function for this in the first place I would just do:

echo empty($d) ? 'null' : $d;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top