【问题标题】:What does question mark (?) before type declaration means in php (?int) [duplicate]类型声明之前的问号(?)在php(?int)中意味着什么[重复]
【发布时间】:2018-03-21 10:43:39
【问题描述】:

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

【问题讨论】:

  • 表示应该是int但也可以是null
  • php 7.2不支持的问题
  • @MaxChernopolsky 您能否提供您声称“php 7.2 不支持 Nullable 类型”的参考?
  • 我错了。确实如此。

标签: php php-7.2


【解决方案1】:

它叫Nullable types

?int 定义为intnull

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

例子:

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

nullOrInt(100);
nullOrInt(null);

函数 nullOrInt 将接受 null 和 int。

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

【讨论】:

  • 所以...它是弱类型强类型? :D
  • @geoidesic 天哪,你用那个 lmao 杀了我
  • 好吧,像 C# 或 Java 这样的语言在请求对象时允许传递 null,因此您可以轻松获得空指针异常,除非您手动验证每个函数的每个参数,因为它们传递了一个 指针。在 PHP 中你必须明确地询问你想要一个对象,或者一个对象或者 null,因为 PHP 传递了一个 reference。从这个意义上说,与那些语言相比,这些参数对我来说似乎更具强类型(除了 PHP 不是静态类型语言这一事实​​之外)。
  • 支持什么版本的php?
  • @MrTo-Kane 可空类型在 PHP 7.1 中引入
猜你喜欢
  • 2016-01-02
  • 1970-01-01
  • 2022-12-12
  • 2012-12-11
  • 2018-07-05
  • 1970-01-01
  • 1970-01-01
  • 2020-06-29
  • 1970-01-01
相关资源
最近更新 更多