What is the meaning of variable length parameters in PHP? Can it be implemented using an array?
曾经蜡笔没有小新
曾经蜡笔没有小新 2017-06-14 10:49:43
0
5
1096
<?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?

曾经蜡笔没有小新
曾经蜡笔没有小新

reply all(5)
習慣沉默

The meaning is that you don’t need to declare an array separately

我想大声告诉你

You can understand it as syntax sugar
func_get_argsIt 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); 
}
}
学霸

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.

我想大声告诉你

redis.lpush scene

public function lPush( $key, $value1, $value2 = null, $valueN = null ) {}
迷茫

It’s just syntactic sugar, with variable parameters. Many languages ​​have implemented it, and PHP has also implemented it

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template