LoginSignup
18

More than 5 years have passed since last update.

PHPで配列そのものを引数にしたい場合

Posted at

引数に配列を指定するのではなく、配列をのものを引数として利用する場合です。

sample.php
$args = array();
foo($args[0], $args[1], $args[2], ……);

このようなイメージです。

call_user_func_array()という関数で実現できるそうです。

使い方

関数を呼ぶ場合

call_function.php
$args = array(1, 2);
call_user_func_array('foo', $args); // 3

function foo($a, $b)
{
    echo $a + $b;
}

メソッドを呼ぶ場合

call_method.php
$args = array(1, 2);

$foo = new Foo();
call_user_func_array(array($foo, 'bar'), $args); // 3

class Foo{
    function bar($a, $b)
    {
        echo $a + $b;
    }
}

$thisとか使えば、同じクラス内のメソッドも呼べるよ!

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
18