svidgen svidgen - 5 months ago 11
PHP Question

How can I tell whether a function returns "nothing" or NULL?

Consider a function that explicitly returns

null
:

function nullreturn() {return null;}
$rv = nullreturn();
var_dump($rv);
var_dump(isset($rv));
var_dump(is_null($rv));


Which identifies as
null
-- as expected.

NULL
bool(false)
bool(true)


And consider a function with no return value -- or even a
return
statement:

function noreturn() {}
$rv = noreturn();
var_dump($rv);
var_dump(isset($rv));
var_dump(is_null($rv));


Which also identifies as
null
:

NULL
bool(false)
bool(true)


... is there a way to determine that
noreturn
returns "nothing" instead of
null
?




As to why I need this
null
/
void
distinction, I've just been trying to achieve compatibility with a previous service implementation that did make this distinction and which includes tests for it. But, it's probably not critical. I just don't want to strip away the relevant tests and hope I wasn't depending on the distinction if I were overlooking an achievable solution.

Answer

No. Not returning, and returning NULL, are the exact same thing. A function with no return value implicitly returns NULL. This applies in many languages. Sorry if this isn't the answer you're looking for, but it is reality.

The following are all the exact same thing:

function A() {
    return;
}

function B() {
    return NULL;
}

function C() {
}

See also return in the PHP manual:

Note: If no parameter is supplied, then the parentheses must be omitted and NULL will be returned. Calling return with parentheses but with no arguments will result in a parse error.