Void Functions


In this video we cover a new feature in PHP 7.1 called Void Functions.

Much like in the Nullable Types video, the idea here is to allow specifying a PHP 7.0 function return type even when returning nothing.

When working through the new features of PHP 7.1 with a developer who is very new to programming in general, not just PHP, we had an interesting discussion around why null is not equivalent to void. There's a fairly well known phrase - at least here in the UK - where you may declare something "null and void".

The problem with this phrase is it's a legal thing. It's not directly related to software development, other than in the words we use.

From my very basic law knowledge, the idea here is that if something is nullified, it is deemed to have never existed. However, to become void, that something must have existed at some point, and has since been cancelled.

Anyway, this is a really good question as return null; and return; are equivalent in PHP. You can test this, even if the outcome looks quite odd:

<?php

function doSomething() : void
{
    return;
}

function anotherThing()
{
    return null;
}

doSomething() === anotherThing(); // true

A function in PHP always returns a value. Even if that value is implicitly null, like in doSomething(). It's built right into the language.

A follow up question may be - well why is it void, and not null? In other words, why this:

<?php

function doSomething() : void

// and not this:

function doSomething() : null

Reading the RFC explains this in further depth. The best answer - for me - is this:

void more clearly conveys that the function is supposed to not return a value, rather than return null specifically.

Taking a step back here, there is another way of looking at Void Functions:

You probably shouldn't be using them.

Contentious?

Of course!

Most of the time (there are always exceptions), I aim to return something from a function. This may be as simple as a true or false, but it's still something. I would encourage others to do the same.

Perhaps the nicest side effect of getting into the habit of using return types and type hints, is in that they make you document your code without having to explicitly write documentation. At any point where you find yourself using void, ask yourself if this is likely to be the most useful output. In my experience, whilst it can feel initially cleaner to return null (or void, in this case), I usually find myself regretting this and refactoring shortly thereafter.

Episodes

# Title Duration
1 Shorthand Destructuring 06:13
2 Nullable Types 06:37
3 Class Constant Visibility 03:15
4 Void Functions 01:53
5 Multi Catch Exception Handling 05:10