Void as return type Void as return type php php

Void as return type


Edit:

A new separate RFC for a void return type has been published, has passed the vote, and was implemented in PHP 7.1.
There is now a void return type in PHP. :)

Original Post:

Taken from wiki.php.net:

Future Work

Ideas for future work which are out of the scope of this RFC include:

  • Allow functions to declare that they do not return anything at all (void in Java and C)

So currently there is no way to declare that you don't return anything.
I don't know what's best in your situation, but I'd probably just go with not declaring the return type for now.

To answer your question whether there will be a void return type in PHP 7:
There is no guarantee yet, but I think it is very likely that void or a synonym will be implemented in some way.


The voidreturn type was accepted for php 7.1. So it will come in the future.

Some examples on how it will work:

function should_return_nothing(): void {    return 1; // Fatal error: A void function must not return a value}function returns_null(): void {    return null; // Fatal error: A void function must not return a value}function lacks_return(): void {    // valid}function returns_nothing(): void {    return; // valid}

See the RFC from Andrea Faulds for more info!


Edit: In PHP 7.1 there is a void pseudo-type. It is defined in the Void Return Type RFC. Below is the pre-7.1 answer.


Author of the return types RFC here. In PHP 7.0 there will not be void return types since the RFC didn't add it and neither did any other RFC targeting PHP 7.0.

The type void can exist in the PHP 7 series if we decide that adding new key/reserved words is okay for minor releases even though they will break code. This is somewhat uncertain, but it was done in PHP 5.4 with the callable keyword.


Personally, I don't think we need void; we already have null. From the manual:

The special NULL value represents a variable with no value. NULL is the only possible value of type null.

In PHP a function which doesn't return anything will implicitly return null. This means that you cannot ever actually return nothing*. Going the null route means that there are no backwards compatibility breaks since null will not be a valid class/interface/trait name starting in PHP 7.0 and doesn't add any new key or reserved words.

*People familiar with the Zend Engine will realize that you can return nothing, but if you returned nothing the variable you are assigning will be assigned null, which makes them logically equivalent.