类型声明前的问号 (?) 在 php (?int) 中意味着什么
What does question mark (?) before type declaration means in php (?int)
我在第 40 行的 https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Console/Output/Output.php 中看到了这段代码,他们正在使用 ?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);
}
叫做Nullable types
。
将 ?int
定义为 int
或 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);
function nullOrInt
将接受 null 和 int。
我在第 40 行的 https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Console/Output/Output.php 中看到了这段代码,他们正在使用 ?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);
}
叫做Nullable types
。
将 ?int
定义为 int
或 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);
function nullOrInt
将接受 null 和 int。