gpt4 book ai didi

php - int $number 和 int $number = null 有什么区别?

转载 作者:行者123 更新时间:2023-12-02 08:19:10 25 4
gpt4 key购买 nike

鉴于此解释

Nullable types: 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.

https://www.php.net/manual/en/migration71.new-features.php

以下代码:


public function test(?int $var) {

}

表示可以使用 $var 作为 intnull 调用 test()

以及以下代码:


public function test(int $var = null) {

}

意味着test()可以用$var作为intnull来调用.

这两种方法有什么区别?其中任何一个比另一个性能更高吗?

最佳答案

区分这里讨论的两种语言特征很重要,即 type declarationsdefault argument values .

第一个函数仅使用类型声明,这意味着输入参数必须类型为int NULL

第二个函数同时使用类型声明和默认参数值,这意味着参数必须类型为intNULL 但是如果省略,则默认为NULL

拿你的第一个函数来说,如果你只是调用 test() 而不传递任何东西给它,你会得到:

PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function test() [...]

这是正确的,因为该函数需要 intNULL 但两者都没有得到,而对于第二个,由于您已经使用默认值定义了参数,它将运行没有错误。

代码

function test(?int $var) {
var_dump($var);
}

function test2(int $var = null) {
var_dump($var);
}

test(1); // fine
test(); // error
test2(1); // fine
test2(); // fine

就性能而言,差异可能可以忽略不计,没有什么大到足以引起关注。

实例

Repl

关于php - int $number 和 int $number = null 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57706198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com