php是什么 - php语法
有什么区别?int $ number和int $ number=null? (2)
鉴于此解释
可空类型:参数和返回值的类型声明现在可以通过在类型名称前面添加问号来标记为可为空。 这表示除了指定的类型外,NULL还可以作为参数传递,或者分别作为值返回。
以下代码:
public function test(?int $var) {
}
表示
test()
可以使用
$var
作为
int
或
null
调用。
以下代码:
public function test(int $var = null) {
}
意味着可以使用
$var
调用
test()
作为
int
或
null
。
这两种方法有什么区别? 这些中的任何一个都比其他更高效吗?
区分这里讨论的两个语言特征,即 类型声明 和 默认参数值很重要 。
第一个函数只使用类型声明,这意味着输入参数
必须
是
int
或
NULL
类型。
第二个函数使用类型声明和默认参数值,这意味着参数
必须
是
int
或
NULL
类型,
但
如果省略它将默认为
NULL
。
拿你的第一个函数,如果你只是调用
test()
而不传递任何东西,你会得到:
PHP致命错误:未捕获ArgumentCountError:函数test()的参数太少[...]
这是正确的,因为函数需要
int
或
NULL
但两者都没有,而对于第二个,因为你已经使用默认值定义了参数,它将运行没有错误。
码
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
就性能而言,差异可能是微不足道的,没有足够的重要性可以引起关注。
实例
区别在于如何调用该函数:
// public function test(?int $var)
$foo->test("x"); // does not work (Argument 1 passed to Foo::test() must be of the type int or null, string given)
$foo->test(123); // works
$foo->test(null); // works
$foo->test(); // does not work (Too few arguments to function Foo::test(), 0 passed)
// public function test(int $var = null)
$foo->test("x"); // does not work (Argument 1 passed to Foo::test() must be of the type int or null, string given)
$foo->test(123); // works
$foo->test(null); // works
$foo->test(); // works
区别在于您不能使用第一种语法将函数调用为
->test()
。