Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if PHP function returns null or nothing

I have this code

 $return = $ep->$method($params);
 if ($return === null) {
  throw new Exception('Endpoint has no return value');
 }
 return $return;

Is there any way to distinguish between a method that returns null and a method that does not return anything?

like image 671
Bart van Heukelom Avatar asked Nov 27 '09 16:11

Bart van Heukelom


3 Answers

It's not possible. When no return value is set the function automatically returns null.

like image 166
William Avatar answered Oct 16 '22 11:10

William


If the function doesn't return anything, then you should not test it's return value. You should know which functions are expected to return something or nothing at all - even if you're not the one who wrote them.

like image 20
Rolf Avatar answered Oct 16 '22 10:10

Rolf


With PHP7’s return type declaration feature:

function a(): void {
    return null; // :(
}

function b(): void {
    // :)
}

function c(): void {
    return; // :)
}
like image 1
Taufik Nurrohman Avatar answered Oct 16 '22 12:10

Taufik Nurrohman