IT박스

PHP 함수에 가변 개수의 인수를 전달하는 방법

itboxs 2020. 7. 28. 08:18
반응형

PHP 함수에 가변 개수의 인수를 전달하는 방법


가변 수의 인수 ( func_num_args()사용 func_get_args()) 를 취하는 PHP 함수가 있지만 함수를 전달하려는 인수의 수는 배열의 길이에 따라 다릅니다. 가변 개수의 인수로 PHP 함수 호출 하는 방법이 있습니까?


배열에 인수가 있으면 함수에 관심이있을 수 있습니다 call_user_func_array.

전달하려는 인수의 수가 배열의 길이에 의존하는 경우 아마도 배열 자체에 인수를 묶을 수 있습니다 call_user_func_array.

전달한 해당 배열의 요소는 함수에서 고유 한 매개 변수로 수신됩니다.


예를 들어,이 기능이 있다면 :

function test() {
  var_dump(func_num_args());
  var_dump(func_get_args());
}

다음과 같이 매개 변수를 배열로 묶을 수 있습니다.

$params = array(
  10,
  'glop',
  'test',
);

그런 다음 함수를 호출하십시오.

call_user_func_array('test', $params);

이 코드는 다음과 같이 출력됩니다.

int 3

array
  0 => int 10
  1 => string 'glop' (length=4)
  2 => string 'test' (length=4)

즉, 3 개의 파라미터; 정확히 iof와 같이 함수가 이런 식으로 호출되었습니다.

test(10, 'glop', 'test');

이것은 이제 PHP의 5.6.x 가능 (일부 언어 플랫 연산자라고도 함) ... 연산자를 사용하여 :

예:

function addDateIntervalsToDateTime( DateTime $dt, DateInterval ...$intervals )
{
    foreach ( $intervals as $interval ) {
        $dt->add( $interval );
    }
    return $dt;
}

addDateIntervaslToDateTime( new DateTime, new DateInterval( 'P1D' ), 
        new DateInterval( 'P4D' ), new DateInterval( 'P10D' ) );

새로운 Php 5.6 에서는을 사용하는 ... operator대신 사용할 수 있습니다 func_get_args().

따라서 이것을 사용하면 전달한 모든 매개 변수를 얻을 수 있습니다.

function manyVars(...$params) {
   var_dump($params);
}

PHP 5.6 부터 ...연산자 로 변수 인수 목록을 지정할 수 있습니다 .

function do_something($first, ...$all_the_others)
{
    var_dump($first);
    var_dump($all_the_others);
}

do_something('this goes in first', 2, 3, 4, 5);

#> string(18) "this goes in first"
#>
#> array(4) {
#>   [0]=>
#>   int(2)
#>   [1]=>
#>   int(3)
#>   [2]=>
#>   int(4)
#>   [3]=>
#>   int(5)
#> }

보시다시피 ...연산자는 변수 인수 목록을 배열로 수집합니다.

변수 인수를 다른 함수에 전달해야하는 경우 ...에도 여전히 도움이 될 수 있습니다.

function do_something($first, ...$all_the_others)
{
    do_something_else($first, ...$all_the_others);
    // Which is translated to:
    // do_something_else('this goes in first', 2, 3, 4, 5);
}

Since PHP 7, the variable list of arguments can be forced to be all of the same type too.

function do_something($first, int ...$all_the_others) { /**/ }

For those looking for a way to do this with $object->method:

call_user_func_array(array($object, 'method_name'), $array);

I was successful with this in a construct function that calls a variable method_name with variable parameters.


You can just call it.

function test(){        
     print_r(func_get_args());
}

test("blah");
test("blah","blah");

Output:

Array ( [0] => blah ) Array ( [0] => blah [1] => blah )


I'm surprised nobody here has mentioned simply passing and extracting an array. E.g:

function add($arr){
    extract($arr, EXTR_REFS);
    return $one+$two;
}
$one = 1;
$two = 2;
echo add(compact('one', 'two')); // 3

Of course, this does not provide argument validation. For that, anyone can use my expect function: https://gist.github.com/iautomation/8063fc78e9508ed427d5


An old question, I know, however, none of the answers here really do a good job of simply answer the question.

I just played around with php and the solution looks like this:

function myFunction($requiredArgument, $optionalArgument = "default"){
   echo $requiredArgument . $optionalArgument;
}

This function can do two things:

If its called with only the required parameter: myFunction("Hi") It will print "Hi default"

But if it is called with the optional parameter: myFunction("Hi","me") It will print "Hi me";

I hope this helps anyone who is looking for this down the road.


Here is a solution using the magic method __invoke

(Available since php 5.3)

class Foo {
    public function __invoke($method=null, $args=[]){
        if($method){
            return call_user_func_array([$this, $method], $args);
        }
        return false;
    }

    public function methodName($arg1, $arg2, $arg3){

    }
}

From inside same class:

$this('methodName', ['arg1', 'arg2', 'arg3']);

From an instance of an object:

$obj = new Foo;
$obj('methodName', ['arg1', 'arg2', 'arg3'])

참고URL : https://stackoverflow.com/questions/1422652/how-to-pass-variable-number-of-arguments-to-a-php-function

반응형