3

I am trying to pass multiple arguments to a custom method which contains a sprintf() method. The arguments I am passing will be used in the sprintf() method. Is there a way to do this? I tried the code below but get "too few arguments".

<?php
function myMethod($text, $args)
{
    echo sprintf($text, $args);
}

myMethod('"%s" is "%s" method', 'This', 'my');
?>
0

1 Answer 1

6

Using vsprintf() rather than sprintf() is at the heart of any solution, because you pass the arguments as an array:

If you're using PHP 5.6, and can use variadics

function myMethod($text, ...$args)
{
    echo vsprintf($text, $args);
}

myMethod('"%s" is "%s" method', 'This', 'my');

Otherwise func_get_args() is your friend:

function myMethod($text)
{
    $args = func_get_args();
    array_shift($args); // remove $text argument from the $args array
    echo vsprintf($text, $args);
}

myMethod('"%s" is "%s" method', 'This', 'my');
Sign up to request clarification or add additional context in comments.

4 Comments

Or you can use call_user_func_array(): function myMethod() { call_user_func_array('printf', func_get_args()); }. It's ugly but it works.
@JovanPerovic - variadics require PHP >= 5.6, but they're a lot cleaner to use than func_get_args(), especially if you have additional arguments that you want to maintain independently of the args array
@JovanPerovic - The flip side of variadics is using "argument unpacking" when calling a function, also very useful - php.net/manual/en/migration56.new-features.php
Absolutely :) I plan to use full potential of short array syntax (v5.4) and this to I am not worried :)

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.