将函数参数从一个函数传递到另一个函数,而不实际键入它们(PHP)

时间:2015-06-25 19:39:18

标签: php parameters reference arguments

我想知道是否可以传递函数参数而不实际重写它们。

<?php

class example()
{
    __construct()
    {
        a("hello", "second_param", "another"); // <--- CALL
    }

    function a($param1, $param2, $param3) // <--- PARAMS
    {
        // call b(), passing this function its parameters
        b( $SOME_NEAT_TRICK_TO_GET_ARGS ) // <--- I WANT TO BE LAZY HERE AND GET ALL THE PASSED PARAMS

        // do something
    }

    function b( $SOME_NEAT_TRICK_TO_GET_ARGS ) // <--- I WANT TO BE LAZY HERE AND JUST PASS THE PARAMS ALONG
    {
        var_dump($param1); // <--- I WANT TO READ THEM HERE
        var_dump($param2);
        var_dump($param3);

        // do something
    }
}

我想以相同的顺序传递数组中的参数。

1 个答案:

答案 0 :(得分:1)

最简单的方法是使用数组作为第二个函数参数。将看起来像这样:

function a () { // As much elements as you want can be passed here (or you can define it fix)
    b(func_get_args());
}


function b ($arr) {
    die(var_dump($arr)); // You have all elements from the call of a() here in their passed order ([0] => ..., [1] => ..., ...)
}