PHP: Void and Null are (not) same thing

Posted: December 13, 2016 in Programming
Tags: ,

Sloppy code is not always a result of bad and lazy developers, sometimes, language runtime can be the one who to blame. One of the examples is PHP and how it treats “void” and “null” in non-strict mode.

I have stumbled upon this example in Symfony official documentation regarding new Security component and new features regarding authentication process:

1
(you can find this code here: http://symfony.com/doc/current/security/guard_authentication.html)

Now, this is very, very wrong – standalone return statement has its semantical meaning: “stop execution of method/function without return value”, basically, it returns nothing, a void.

However, comment in code says “return null“. So what is here wrong, code or comment?

Well, in PHP world, everything presented in code snippet is correct and everything is terribly wrong (presumably that we work in non-strict execution environment, of course).

This is possible because every return statement in PHP without argument is evaluated to “null“. So, per example, by using example above:

$auth = new TokenAuthenticator();
$result = $auth->getCredentials($request);
var_dump($result);

would evaluate to “null“!

Knowing that “null” is pointer that does not refers to a valid address (see: https://en.wikipedia.org/wiki/Null_pointer) and that “void” is absence of any information (see: https://en.wikipedia.org/wiki/Void_type) we know that:

// pseudocode
null == void => false
null != void => true
null !== void => true

And because of that, this code:

$auth = new TokenAuthenticator();
$result = $auth->getCredentials($request);

should throw exception in, preferably, compile time.

However, in PHP – this is absolutely valid code, and execution result is valid value, even though it is more than obvious that this is a language bug. Unfortunately, fixing this bug would crash half of the internet.

So, just because you can something, does not mean you should, so if you need to return “null“, do that explicitly in your code:

return null;

and do that always! If language treats “void” and “null” as same, we (developers) don’t. When we see a method with “return” statement only, we see a procedure, not a function and we instantly guess that that method is command (not query) and it will not return result.

Language can be buggy – but our code doesn’t have to.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s