In PHP, is it possible to replicate the way that isset() suppresses warnings for undefined variables in its arguments?

77 Views Asked by At

With the isset() function, you can pass undefined variables to its arguments without getting a warning. I was wondering if it is possible to replicate this functionality somehow.

For instance, I tried to make a function that combines isset($value) && is_array($value).

However, if I try to test it with an undefined variable, I get a "Warning: Undefined variable $somevar" warning.

function isset_array(mixed $value): bool
{
    if (isset($value) && is_array($value)) {
        return TRUE;
    } else {
        return FALSE;
    }
}

var_dump(isset_array($somevar));

I don't get the same warning with isset().

var_dump(isset($somevar));

I assume that this is some hardcoded behavior in isset().

Is it possible to replicate this behavior? Or is this some hardcoded PHP functionality that you can't mimic?

1

There are 1 best solutions below

2
Karl Hill On BEST ANSWER

One possible workaround is to pass the variable by reference. This will prevent the "Undefined variable" notice from being generated when you pass an undefined variable to the function.

function isset_array(&$value): bool
{
    return isset($value) && is_array($value);
}

var_dump(isset_array($somevar));