其他语言大多都有函数传参解包的功能,php8也加入了这个功能。
- php version < 8
<?php
function test(...$arg) {
var_dump($arg);
}
test();
//array(0) { }
test(NULL);
//array(1) { [0]=> NULL }
test("foo", "bar");
//array(2) { [0]=> string(3) "foo" [1]=> string(3) "bar" }
test(NULL, array(), "dummy");
//array(3) { [0]=> NULL [1]=>[] [2]=> string(5) "dummy" }
function test1($a, $b = NULL, $c = NULL, $d = NULL, $e = NULL) {
var_dump($a, $b, $c, $d, $e);
}
$arg = array(
"First arg",
NULL, NULL, NULL,
"Fifth arg",
);
test1(...$arguments);
// string(14) "First arg"
// NULL
// NULL
// NULL
// string(14) "Fifth arg"
- php version >=8
<?php
function dummy($a, $b = NULL, $c = NULL, $d = NULL, $e = NULL) {
var_dump($a, $b, $c, $d, $e);
}
dummy(a:"dummy", e:"foo");
// string(5) "dummy"
// NULL
// NULL
// NULL
// string(3) "foo"