Should a function use: return null;?
Solution 1:
Always is a good practice to show what you're returning.
But as a tip, the following are all equivalent:
function test()
{
return null;
}
function test()
{
return;
}
function test()
{
}
In all cases there for var_dump(test());
will be:
NULL
Solution 2:
If you don't return anything, just use return;
or omit it at all at the end of the function.
If your function is usually returns something but doesn't for some reason, return null;
is the way to go.
That's similar to how you do it e.g. in C: If your function doesn't return things, it's void
, otherwise it often return either a valid pointer or NULL.
Solution 3:
It is just plain silly to return null
if there is nothing to return. Doing return;
shows intend of not actually returning anything. And makes it clear what the function does.
The fact that PHP does not have a void
return type yet should not be a reason to make the intend less clear. Also note that PHP 7.1 will provide support for the void
return type:
function test(): void {
return null; // this will error
}