Gar*_*yle 12 php variadic-functions php-7
我有一个在PHP 7中定义的varargs类型方法
function selectAll(string $sql, ...$params) { }
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,当我已经有一个数组时,有时我想调用这个方法,我不能直接将数组变量传递给这个方法.
Tha*_*lan 20
使用splat运算符解压缩数组参数,就像在函数中使用一样:
selectAll($str, ...$arr);
Run Code Online (Sandbox Code Playgroud)
像这样:
function selectAll(string $sql, ...$params) {
print_r(func_get_args());
}
$str = "This is a string";
$arr = ["First Element", "Second Element", 3];
selectAll($str, ...$arr);
Run Code Online (Sandbox Code Playgroud)
打印:
Array
(
[0] => This is a string
[1] => First Element
[2] => Second Element
[3] => 3
)
Run Code Online (Sandbox Code Playgroud)
为此而感恩.
如果你不在参数中使用splat运算符,你最终会这样
归档时间: |
|
查看次数: |
4127 次 |
最近记录: |