在php(?int)中类​​型声明之前的问号(?)是什么

Jag*_* NH 18 php php-7.2

我在https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Console/Output/Output.php他们使用的第40行看到了这段代码?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);
    }
Run Code Online (Sandbox Code Playgroud)

Ata*_*man 29

它被称为Nullable types.

其中定义?intintnull.

现在,通过在类型名称前加上问号前缀,可以将参数和返回值的类型声明标记为可为空.这表示除了指定的类型外,NULL还可以作为参数传递,或者分别作为值返回.

示例:

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

nullOrInt(100);
nullOrInt(null);
Run Code Online (Sandbox Code Playgroud)

函数nullOrInt将接受null和int.

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

  • 那么...它是弱类型强类型吗?:D (2认同)
  • 好吧,像 C# 或 Java 这样的语言在请求对象时允许传递 null,因此您可以轻松获得空指针异常,除非您手动验证每个函数的每个参数,因为它们传递的是*指针*。在 PHP 中,您必须明确询问您想要一个对象、一个对象还是 null,因为 PHP 传递一个*引用*。从这个意义上说,与那些语言相比,这些参数对我来说似乎是更强类型的(除了 PHP 不是静态类型语言这一事实​​)。 (2认同)