PHP Overload like sprintf ()?

How do you write a function in PHP that can take an unlimited number of arguments like sprintf?

sprintf("one:%s",$one);
sprintf("one:%s two:%s",$one,$two);
...
+3
source share
4 answers

func_get_args()

Example from php.net

function foo()
{
    $numargs = func_num_args();
    echo "Number of arguments: $numargs<br />\n";
    if ($numargs >= 2) {
        echo "Second argument is: " . func_get_arg(1) . "<br />\n";
    }
    $arg_list = func_get_args();
    for ($i = 0; $i < $numargs; $i++) {
        echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
    }
}

foo(1, 2, 3);
+3
source

Easy. Declare your function with static arguments

function myprintf ($string)

and get unlimited extra arguments using func_get_args () .

+1
source

A function can take as many parameters as you want; he just has to deal with them, using the following functions: func_num_args, func_get_argand func_get_args.

Examples are given on these three pages of the manual, but here is one of the page func_get_args(citation):

function foo()
{
    $numargs = func_num_args();
    echo "Number of arguments: $numargs<br />\n";
    if ($numargs >= 2) {
        echo "Second argument is: " . func_get_arg(1) . "<br />\n";
    }
    $arg_list = func_get_args();
    for ($i = 0; $i < $numargs; $i++) {
        echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
    }
}

foo(1, 2, 3);

And the output will be:

Number of arguments: 3<br />
Second argument is: 2<br />
Argument 0 is: 1<br />
Argument 1 is: 2<br />
Argument 2 is: 3<br />
+1
source
0
source

Source: https://habr.com/ru/post/1732686/


All Articles