0

I have a function that is always called like this:

old_function(sprintf("Some arbitrary data %d, %s, %f\n", $i, $s, $f));

Is it possible in PHP to make a function that combines these to functions for

new_function("Some arbitrary data %d, %s, %f\n", $i, $s, $f);

In the beginning of new_function, the variable argument list of the function would have to be parsed and passed to sprintf internally:

function new_function( /* variable argument list */ )
{
     $string = sprintf( /* variable argument list */ );
     return old_function($string);
}

Is it possible in PHP?

3 Answers 3

3

You can use func_get_args() & call_user_func_array() for this:

function new_function()
{
     // get all function arguments
     $args = func_get_args();
     // run the function "sprintf" with the given arguments
     $string = call_user_func_array("sprintf", $args);
     return old_function($string);
}
Sign up to request clarification or add additional context in comments.

Comments

2

As of PHP 5.6, you can try to use Variadic Functions via ... operator. This new feature enables native support for passing variable-length argument lists to any function.

Try something like this:

public function new_function(...$params) {
    $string = call_user_func_array("sprintf", $params);
    return old_function($string);
}

Comments

0

Please look into func_get_args() method. Which can retrieve variable length arguments.

1 Comment

That's nice, but that does not tell me how to actually pass the arguments to sprintf

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.