类型声明之前的问号(?)在php(?int)中意味着什么 [英] What does question mark (?) before type declaration means in php (?int)

查看:295
本文介绍了类型声明之前的问号(?)在php(?int)中意味着什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在中看到了此代码他们正在使用?int的https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Console/Output/Output.php 行号40.

public function __construct(?int $verbosity = self::VERBOSITY_NORMAL, bool $decorated = false, OutputFormatterInterface $formatter = null)
    {
        $this->verbosity = null === $verbosity ? self::VERBOSITY_NORMAL : $verbosity;
        $this->formatter = $formatter ?: new OutputFormatter();
        $this->formatter->setDecorated($decorated);
    }

推荐答案

它称为Nullable types.

?int定义为intnull.

现在,可以通过在类型名称前加上问号来将

用于参数和返回值的类型声明标记为可为空.这表示与指定的类型一样,NULL可以分别作为参数传递或作为值返回.

Type declarations for parameters and return values can now be marked as nullable by prefixing the type name with a question mark. This signifies that as well as the specified type, NULL can be passed as an argument, or returned as a value, respectively.

示例:

function nullOrInt(?int $arg){
    var_dump($arg);
}

nullOrInt(100);
nullOrInt(null);

函数nullOrInt将同时接受null和int.

function nullOrInt will accept both null and int.

参考: http://php.net/manual/zh/migration71. new-features.php

这篇关于类型声明之前的问号(?)在php(?int)中意味着什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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