Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

python - unpacking an array of arguments in php

Python provides the "*" operator for unpacking a list of tuples and giving them to a function as arguments, like so:

args = [3, 6]
range(*args)            # call with arguments unpacked from a list

This is equivalent to:

range(3, 6)

Does anyone know if there is a way to achieve this in PHP? Some googling for variations of "PHP Unpack" hasn't immediately turned up anything.. perhaps it's called something different in PHP?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In php5.6 Argument unpacking via ... (splat operator) has been added. Using it, you can get rid of call_user_func_array() for this simpler alternative. For example having a function:

function add($a, $b){
  return $a + $b;
}

With your array $list = [4, 6]; (after php5.5 you can declare arrays in this way).

You can call your function with ...:

echo add(...$list);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...