简体   繁体   中英

Passing function arguments from one function to another, without actually typing them (PHP)

I was wondering if it is possible to pass function arguments without actually rewriting them.

<?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
    }
}

I'd like to pass the parameters in an array in the same order.

The simplest thing is to use an array for the second function parameter. Will looks like this:

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] => ..., ...)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM