Void as return type

Daan picture Daan · Apr 22, 2015 · Viewed 48.9k times · Source

I was testing return types with PHP 7.

I've created a simple script to test return types of PHP 7:

<?php

Class Obj {

    public function __construct(){

    }

    public function test(): string { //a string needs to be returned
        return "ok";
    }

}

function foo(): Obj { //instance of Obj needs to be returned
    return new Obj();
}

$o = foo();
echo $o->test(); // output: ok

Now in other programming languages when you specify a return type void it means you cannot return anything or you will get an error. So I wrote this script:

<?php

    function foo(): void {

    }

    foo(); 

Now in above script the expected output is nothing. Instead it gives me a Fatal error:

Fatal error: Return value of foo() must be an instance of void, none returned on line 2

My question is (I couldn't find it), in PHP 7 will there be a similar void type?

Answer

Siguza picture Siguza · Apr 22, 2015

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.