LoginSignup
1
1

More than 1 year has passed since last update.

phpで配列から引数を自動展開する方法

Posted at

可変長引数の話題でよく目にする、関数の引数は以下の通り。

function hoge(...$array)
{
    var_dump($array);
}

hoge('hoge', 'piyo', 'hello', 'world');

array(4) {
  [0]=>
  string(4) "hoge"
  [1]=>
  string(4) "piyo"
  [2]=>
  string(5) "hello"
  [3]=>
  string(5) "world"
}

'...'入力時に引数を配列から自動展開してくれる機能がある。
この際、配列鍵が歯抜けでも問題がない。

$array = ['hoge', 'piyo', 'hello', 'world'];
もしくは
$array = ['hoge', 'piyo', 'hello'];
これを関数の引数としたい

hoge(...$array);

array() {
  [0]=>
  string(4) "hoge"
  [1]=>
  string(4) "piyo"
  [2]=>
  string(5) "hello"
...

function humu($one, $two, $three){
var_dump('one', $one, 'two', $two, 'three', $three);
}
$array = ['hoge', 'piyo', 'hello', 'world'];
unset($array[0]);
humu(...$array);
string(3) "one"
string(4) "piyo"
string(3) "two"
string(5) "hello"
string(5) "three"
string(5) "world"

ちなみに引数名を指定しない場合は、配列鍵が入る。

hoge(...["one" => 'hoge', "two" => 'piyo', "three" => 'hello', "four" => 'world']);
array(4) {
  ["one"]=>
  string(4) "hoge"
  ["two"]=>
  string(4) "piyo"
  ["three"]=>
  string(5) "hello"
  ["four"]=>
  string(5) "world"
}

配列鍵と固定引数がある場合は、配列鍵が指定されているとエラーが生じる。

function fuga($Hi, $Fu, $Mi, $four, ...$hoka){
echo "Hi . $Hi\n";
echo "Fu . $Fu\n";
echo "Mi . $Mi\n";
echo "four . $four\n";
var_dump($hoka);
}
//error
fuga(...["one" => 'hoge', "two" => 'piyo', "three" => 'hello', "four" => 'world']);

これは通る
fuga(...['hoge', 'piyo', 'hello', 'world', 'aa' => 'fumu']);
Hi . hoge
Fu . piyo
Mi . hello
four . world
array(1) {
  ["aa"]=>
  string(4) "fumu"
}

最後に可変長引数が設定されているObject内の関数をReflectionClassで覗くと以下のようになっている。


class Object{
function fiction(...$one){
}}

(new \ReflectionClass('\NameSpace\Object'))->getMethod('fiction')->getparameters();
= [
    ReflectionParameter {
      +name: "one",
      position: 0,
      isVariadic: true,
    },
  ]
# Variadic (可変長引数)
(new \ReflectionClass('\NameSpace\Object'))->getMethod('fiction')->getparameters()[0]->isVariadic();
= true
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1