Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Void as return type

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?

like image 903
Daan Avatar asked Apr 22 '15 09:04

Daan


2 Answers

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!

like image 34
acrobat Avatar answered Sep 24 '22 11:09

acrobat


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.

like image 83
Siguza Avatar answered Sep 24 '22 11:09

Siguza