svidgen
svidgen

Reputation: 14302

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.

Upvotes: 2

Views: 82

Answers (1)

Will
Will

Reputation: 24709

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 each do 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.

Upvotes: 5

Related Questions