What does question mark (?) before type declaration means in php (?int) [duplicate]

好久不见. 提交于 2019-11-26 23:20:50

问题


This question already has an answer here:

  • Predefined types of variable parameters 4 answers

I have seen this code in https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Console/Output/Output.php line number 40 they are using ?int.

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);
    }

回答1:


It's called Nullable types.

Which defines ?int as either int or 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.

Example :

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

nullOrInt(100);
nullOrInt(null);

function nullOrInt will accept both null and int.

Ref: http://php.net/manual/en/migration71.new-features.php



来源:https://stackoverflow.com/questions/49404191/what-does-question-mark-before-type-declaration-means-in-php-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!