views:

218

answers:

2

I want to try and write a function to automate some of the legwork in checking/declaring a variable i.e.

function checkVariable($var)
{
if(!isset($var)||empty($var))
    {
    return '';
    }
else
    {
    return $var;
    }
}

$myvar = checkVariable($myvar);

obviously, this isn't going to work, because the variable doesn't exist prior to declaration and throws an error when you use it as an argument - sooooo, is there a way of doing this?

+7  A: 

Pass the variable by reference:

function checkVariable(&$var) {
    // …
}
Gumbo
A: 

I tend to use

$myvar = (isset($myvar) && !empty($myvar)) ? $myvar : '';

But if you have to do this a lot, and you want to use a function, Gumbo's suggestion is right.

Lex