<?php
function test(...$args)
{
print_r($args);
}
test(1,2,3);
//输出
Array
(
[0] => 1
[1] => 2
[2] => 3
)
?>
You can put the parameters into the array when calling test
What is the necessity of this new feature?
我想大声告诉你2017-06-14 10:51:43
You can understand it as syntax sugarfunc_get_args
It can be implemented, but sometimes it is not so elegant
function sort($mode,...$args) {
if($mode === SORT_DESC) {
print_r($args);
}
}
function sort() {
$args = func_get_args();
if($args[0] === SORT_DESC){
array_shift($args);// 去除mode
print_r($args);
}
}
欧阳克2017-06-14 10:51:43
For example, when you want to call an interface, the service addresses of many interfaces are the same, but they are executed by their respective classes and methods. If you want to encapsulate, you cannot determine the parameter type and number. For example, $className is your specific one. Class, $actionName is the method executed in the class
call_user_func_array([$className, $actionName], $params)
In this way, it is difficult for you to handle various parameters in one place. The convenient thing is that when writing the specific call interface, the parameters are passed according to the rules, but the actual call and return are uniformly transmitted by $params. Although PHP is of the same type, the interface you call may be written in other static languages, and the type must be consistent.
Of course, if you only use it once, you can just pass the variable directly, no need to bother.
我想大声告诉你2017-06-14 10:51:43
redis.lpush
scene
public function lPush( $key, $value1, $value2 = null, $valueN = null ) {}
迷茫2017-06-14 10:51:43
It’s just syntactic sugar, with variable parameters. Many languages have implemented it, and PHP has also implemented it