Home  >  Article  >  Backend Development  >  PHP 7.0中,目前不能定义函数的返回类型为null或者void

PHP 7.0中,目前不能定义函数的返回类型为null或者void

WBOY
WBOYOriginal
2016-06-20 12:35:243187browse

TL;DR:

  • 在PHP 7.0下,不要将函数的返回值声明为null或者void,在PHP7.1下可以。
  • 目前函数返回值不可被声明为nullable。

引子

今天有开发同学遇到了定义返回值为null的函数无法被load的问题:

Cannot use ‘App\null’ as class name as it is reserved

追查发现,是因为函数的返回值被声明为了null。

追查

首先,看看返回值到底能不能声明为null:

在RFC PHP RFC: Return Type Declarations中的Future Work中说:

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

这说明此RFC并不支持声明返回值为null或者void!

但是 PHP RFC: Void Return Type则表示支持void表示没有任何返回值,但是不允许用null来声明!(还给了原因)

此RFC会在PHP 7.1中实现,所以目前在PHP 7.0中还不能使用。

PS:经过实验,PHP7.0中,声明返回值为void可以通过语法检查,但是无论怎么返回都会报错(无论是直接return还是不返回):

Return value of App\User::func() must be an instance of void, none returned

更远一点,关于声明返回值为nullable的问题,现在还在草稿阶段,还有很长的路要走: PHP RFC: Declaring Nullable Types。

PS

在 RFC:Return Type Declarations中的Future Work中有:

Improve runtime performance by doing type analysis.

所以目前声明类型更多的是考虑方便开发,借此提升性能 仅仅是在下一步计划中而已。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn