Passing variable argument list to sprintf() - php

I would like to write a function that (amongst other things) accepts a variable number of arguments and then passes them to sprintf().
For example:
<?php
function some_func($var) {
// ...
$s = sprintf($var, ...arguments that were passed...);
// ...
}
some_func("blah %d blah", $number);
?>
How do I do this in PHP?

function some_func() {
$args = func_get_args();
$s = call_user_func_array('sprintf', $args);
}
// or
function some_func() {
$args = func_get_args();
$var = array_shift($args);
$s = vsprintf($var, $args);
}
The $args temporary variable is necessary, because func_get_args cannot be used in the arguments list of a function in PHP versions prior to 5.3.

use a combination of func_get_args and call_user_func_array
function f($var) { // at least one argument
$args = func_get_args();
$s = call_user_func_array('sprintf', $args);
}

Or better yet (and a bit safer too):
function some_func(string $fmt, ... $args) {
$s = vsprintf($fmt, $args);
}
This is PHP 7.4, not sure if it works in earlier versions.

use $numargs = func_num_args();
and func_get_arg(i) to retrieve the argument

Here is the way:
http://www.php.net/manual/en/functions.arguments.php#functions.variable-arg-list
basically, you declare your function as usual, without parameters, then you call func_num_args() to find out how many arguments they passed you, and then you get each one by calling func_get_arg() or func_get_args(). That's easy :)

Related

How can I find the arguments in a php function?

I know how to check with func_num_args for the number of arguments for a function, but how can I get these arguments inside the php function:
<?php
function test() {
echo func_num_args(); //returns 2
echo $argv[1]; //this doesn't work
}
test("aa","bb");
?>
You can call func_get_args() to obtain the array of arguments passed to the function.
For your example, simply add
$args = func_get_args();
And it should work as intended.
There also is func_get_arg, which returns a single argument:
echo func_get_arg(1); // prints second argument
For PHP 5.6+ you can use: ... like this:
function xy(...$args) {
foreach($args as $arg)
echo $arg . "<br />";
}
For more information about this see the manual: http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list

Pass-by-reference for functions with varying length of functions

I have a function with optional number of arguments, something like this:
function DoSomething()
{
$args = funct_get_args();
// and the rest of function
}
In the function above, how can I define the first argument to be passed by reference?
So when I calling it, I be able to do so:
DoSomething(&$first, $second, $third);
Simply declare it in the parameter list:
function DoSomething(&$first) {
$args = func_get_args();
// and the rest of function
}
DoSomething($first, $second, $third);

passing multiple arguments to function php

Apologies for the newbie question but i have a function that takes two parameters one is an array one is a variable function createList($array, $var) {}. I have another function which calls createList with only one parameter, the $var, doSomething($var); it does not contain a local copy of the array. How can I just pass in one parameter to a function which expects two in PHP?
attempt at solution :
function createList (array $args = array()) {
//how do i define the array without iterating through it?
$args += $array;
$args += $var;
}
If you can get your hands on PHP 5.6+, there's a new syntax for variable arguments: the ellipsis keyword.
It simply converts all the arguments to an array.
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
Doc: ... in PHP 5.6+
You have a couple of options here.
First is to use optional parameters.
function myFunction($needThis, $needThisToo, $optional=null) {
/** do something cool **/
}
The other way is just to avoid naming any parameters (this method is not preferred because editors can't hint at anything and there is no documentation in the method signature).
function myFunction() {
$args = func_get_args();
/** now you can access these as $args[0], $args[1] **/
}
You can specify no parameters in your function declaration, then use PHP's func_get_arg or func_get_args to get the arguments.
function createList() {
$arg1 = func_get_arg(0);
//Do some type checking to see which argument it is.
//check if there is another argument with func_num_args.
//Do something with the second arg.
}

passing arguments with an array based object method call

I need to call a method from within a function, so I must pass it as an array like so:
array($this, 'display_page');
but I need to pass arguments along with it. Is this possible?
EDIT - New Method - Still not working.
I have now tried passing an anonymous function, in place of the array call back.
function(){MyClass::display_page($display);}
and edited the function thusly:
class MyClass{
static function display_page($arg = false)
{
if($arg){
echo $arg;
} else {
echo "Nothing to report!";
}
}
}
but all I get is Nothing to report!
EDIT The problem lies with the way the callback was being used within Wordpress (didn't think it was relevant, turns out it was). Have voted to close.
If you take a look at call_user_func, you can see that it has a second optional parameter called parameter.
mixed call_user_func ( callback $function [, mixed $parameter [, mixed $... ]] )
Use that.
Or you could do it the dirty way like mentioned in the comment on call_user_func
$method_name = "AMethodName";
$obj = new ClassName();
$obj->{$method_name}();
Maybe something along these lines will do:
class Foo {
public function callMe() {
$args = func_get_args();
var_dump($args);
}
public function getCallback() {
$that = $this;
return function ($oneMoreArg) use ($that) {
$that->callMe(1, 2, $oneMoreArg);
};
}
}
$foo = new Foo;
$callback = $foo->getCallback();
$callback(3);
If you're not running PHP 5.3, the best you can do is probably return a "custom callback array" and "custom call it":
$callback = array($this, 'callMe', 1, 2);
$args = array_splice($callback, 2);
$args[] = 3;
call_user_func_array($callback, $args);

Call a constructor from variable arguments with PHP

I have a function that takes variadic arguments, that I obtain from func_get_args().
This function needs to call a constructor with those arguments. However, I don't know how to do it.
With call_user_func, you can call functions with an array of arguments, but how would you call a constructor from it? I can't just pass the array of arguments to it; it must believe I've called it "normally".
Thank you!
For PHP < 5.3 it's not easily doable without first creating an instance of the class with call_user_func_array. However with Reflection this is pretty trivial:
$reflection = new ReflectionClass( 'yourClassName' );
$instance = $reflection->newInstanceArgs( $yourArrayOfConstructorArguments );
If for some reason you can not use ReflectionClass::newInstanceArgs here is another solution using eval():
function make_instance($class, $args) {
$arglist = array();
$i = 0;
foreach($args => &$v) {
$arglist[] = $n = '_arg_'.$i++;
$$n = &$v;
}
$arglist = '$'.implode(',$',$arglist);
eval("\$obj = new $class($arglist);");
return $obj;
}
$instance = make_instance('yourClassName', $yourArrayOfConstructorArguments);
Note that using this function enables you to pass arguments by reference to the constructor, which is not acceptable with ReflectionClass::newInstanceArgs.

Categories