无效作为返回类型 [英] Void as return type

查看:78
本文介绍了无效作为返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PHP 7测试返回类型.

I was testing return types with PHP 7.

我创建了一个简单的脚本来测试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

现在在其他编程语言中,当您指定返回类型void时,这意味着您无法返回任何内容,否则会出现错误.所以我写了这个脚本:

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:

致命错误:foo()的返回值必须是void的实例,第2行没有返回

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

我的问题是(我找不到它),在PHP 7中是否会有类似的void类型?

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

推荐答案

针对 void返回类型的新的单独RFC已发布,已通过投票并已在PHP中实现7.1.
PHP中现在有一个void返回类型. :)

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. :)

来自 wiki.php.net :

未来的工作

超出本RFC范围的未来工作的想法包括:

Future Work

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

  • 允许函数声明它们根本不返回任何东西(在Java和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.

要回答您的问题,PHP 7中是否会有void返回类型:
还没有保证,但是我认为很有可能将以某种方式实现void或同义词.

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.

这篇关于无效作为返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆