PHP7中的可空返回类型 [英] Nullable return types in PHP7

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

问题描述

PHP 7引入了返回类型声明.这意味着我现在可以指示返回值是某个类,接口,数组,可调用或新暗示的标量类型之一,对于函数参数来说可能是这样.

PHP 7 introduces return type declarations. Which means I can now indicate the return value is a certain class, interface, array, callable or one of the newly hintable scalar types, as is possible for function parameters.

function returnHello(): string {
    return 'hello';
}

通常会发生值并不总是存在的情况,并且您可能返回某种类型的值或null.虽然可以通过将参数的默认值设置为null(DateTime $time = null)来使参数为可空,但似乎没有办法对返回类型执行此操作.确实是这种情况,还是我不知怎么做呢?这些不起作用:

Often it happens that a value is not always present, and that you might return either something of some type, or null. While you can make parameters nullable by setting their default to null (DateTime $time = null), there does not appear to be a way to do this for return types. Is that indeed the case, or am I somehow not finding how to do it? These do not work:

function returnHello(): string? {
    return 'hello';
}

function returnHello(): string|null {
    return 'hello';
}

推荐答案

PHP 7.1现在支持

PHP 7.1 Now supports nullable return types. The first RFC I linked to is the one they went for:

function nullOrString(int $foo) : ?string
{
    return $foo%2 ? "odd" : null;
}


旧答案:

由于我的评论实际上是对该问题的解答:


old answer:

Since my comment was actually an answer to the question:

PHP 7尚不支持可为null的返回类型,但是有一个RFC 为了解决这个问题,它的目标是加入PHP 7.1.如果通过,则语法将影响所有类型提示(返回类型和类型提示):

PHP 7 won't support nullable return-types just yet, but there's an RFC out to address just that, it aims to land in PHP 7.1. If it passes, the syntax would then affect all type-hints (both return types and type-hints):

public function returnStringOrNull(?array $optionalArray) : ?string
{
    if ($optionalArray) {
        return implode(', ', $optionalArray);//string returned here
    }
    return null;
}

还有竞争的RFC 可以添加联合类型,从而能够执行相同的操作东西,但看起来会有所不同:

There's also a competing RFC to add union types, which would be able to do the same thing, but would look different:

public function returnStringOrNull(array|null $optionalArray) : string|null
{
    if ($optionalArray) {
        return implode(', ', $optionalArray);//string returned here
    }
    return null;
}

不过,现在您必须写:

public function returnStringOrNull( array $optionalArray = null)
{
    if ($optionalArray) {
        return implode(', ', $optionalArray);
    }
}

或者只返回一个空字符串以与返回类型保持一致,然后检查falsy值:

Or just return an empty string to be consistent with the return type, and check falsy value:

public function returnStringOrNull( array $optionalArray = null) : string
{
    if ($optionalArray) {
        return implode(', ', $optionalArray);
    }
    return '';
}
//call
$string = $x->returnStringOrNull();
if (!$string) {
    $string = $x->returnStringOrNull(range(1, 10));
}

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

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