I'm currently looking for a way to give arguments to a function dynamically.
Some code to explain:
//Class: ClassXY
PUBLIC function function1($arg1, $arg2, $arg3);
PUBLIC function function2($arg1);
I currently call it like this:
// $method = 'function1' or 'function2'
echo ClassXY :: {$method}($parameter_string);
My problem is, that parameter_string either is a simple string, that contains the argument or an array that contains all the arguments I want to give to the function. For instance:
$parameter_string: array(3) {[0] => 'arg1', [1] => 'arg2', [2] => 'arg3' }
So far so good. My Problem is, that the call will only work with ClassXY :: function2() since it only expects one argument. If I call ClassXY :: function2() it wont work, since it expects three arguments but only one argument (the array with the three elements, that are supposed to be the three arguments) is given. I need a way to make php realize that each element of the array shall be one argument. Any Ideas?
Thanks in advance!
It looks like call_user_func_array is what you need.
http://php.net/manual/en/function.call-user-func-array.php
Related
I'm kinda confused about optional parameters, or setting a parameter within the function in general. So I found this example:
<?php
function makecoffee($type = "cappuccino")
{
return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
?>
and I don't understand why echo makecoffe("espresso") returns espresso and not cappuccino. Wouldn't espresso be overwritten when calling the method? In my head $type would first be espresso but would then be set to cappuccino since it happens after calling the method. It's kind of hard to explain what I mean, but does $type = "cappuccino" only get called when there's no parameter or why does this happen? Same with
function makecoffee($type = null)
{
}
echo makecoffe("espresso");
why would this return espresso and not null even though type would be set to null when calling the function?
Good example to inform you how exactly the php parameters in functions works, would be the func_get_args() which returns all passed arguments to function.
And this will be our example function.
function foo($example = 'default')
{
print_r(func_get_args());
}
Now we can check if any argument was passed to function.
What happens if we don't pass any argument?
foo();
// Output
Array
(
)
We know that function was called without any argument because output array is empty.
And that is the moment where default value is used for our function parameter. So finally the value for $example parameter will be equal to 'default'
Now we will try to pass 2 arguments to function.
foo('example', 'unnecessary');
// Output
Array
(
[0] => example
[1] => unnecessary
)
From this example we can deduce that we can pass any amount of arguments without seeing an exception. This is one of php features.
But which was passed to $example parameter?
As php docs informs.
The arguments are evaluated from left to right.
The left side for our example is the value from an array with index 0 and the right side is the last element with (actually index 1)
So, under $example we well have 'example' value.
In defaults, the second argument will be ignored because our function doesn't have corresponding second parameter.
What if we pass null as a argument?
This may be tricky because we can imagine that function called with null as a argument will affect on our function as function called without any arguments.
Nothing more wrong.
foo(null);
// Output
Array
(
[0] =>
)
Now you should see that. Despite the fact that our argument was null, value was passed into our function and overwrited default 'example' value for parameter. Finally $example parameter will be equal to null.
That's because the $param = 'value' bit in the function declaration is not executed every time the function is called.
It only comes into play if you don't pass a value for that parameter.
Instead of reading it as a literal assignment PHP does something along the lines of the following under the hood whenever it enters your function.
if true === $param holds no value
$param = 'value'
endif
In other words, $param = 'value' is not a literal expression within the context of the language but rather a language construct to define the desired behaviour of implementing fallback default values.
Edit: Note that the snippet above is deliberately just pseudo code as it's tricky to accurately express what's going using PHP on once PHP has been compiled. See the comments for more info.
I want to be able to call a php function, but only if the number of elements input, matches the number of elements accepted by the function and if it does match i want to pass them 1 by 1 and not as an array.
Currently i have the following code which does the job, but is messy.
call_user_func($functionname, $vars);
This was hitting problems when i had a function that expected an array of 4 elements, but was only passed 3. Having to check and make sure all the vars exist makes writing functions a bit messy. I have a better solution based on reflection. how to dynamically check number of arguments of a function in php , but im one final step short. If the number of arguments matches the number of arguments in a function, i can call that method, but i dont know how to call that method correctly. I have an array of variables. I need to pass these into the function so that I can do something like the following.
function foo($var1, $var2, $var3)
{
//I know all 3 vars exist and dont need to verify first
}
if(count($arrayof3elements) == get_method_var_count("foo") {
dynamically_call_method("foo", $arrayof3elements);
}
Instead of using call_user_func, use call_user_func_array - this allows you to pass an array of arguments, but passes them to the method as separate things.
function x($foo, $bar) {
echo $foo . $bar;
}
call_user_func_array('x', ['abc', 'def']); // prints abcdef
I've a soap function which expects 3 parameters that should be passed as strings with quotes.
function('id','username','password');
and in another hand i've an array which contains :
[0] = > "'id','username','password'"
[1] = > "'id','username','password'"
....
when i echo $array[0] out put is 'id','username','password' and when i use function('id','username','password'); there is no problem but when i use
function($array[0]); it won't work.
i tested my array with echo, die, print_r ... the output is the same as the function expects!!!!
any help ?
thanks ; )
Simply because it can't work. If you have a function that needs 3 parameters, you can't pass a single parameter. Also if is an array that contains the 3 parameters you need, the function still want and need 3 parameters. Thus, if you give the function an array, it will use just the array as the first one (so you'll have an unexpected behavior) and take the second and the thirs as NULL.
It's true that php is a little bit magic, but can't do miracles.
You need to change the signature of your function.
function('id','username','password');
is a function with three parameters.
function($array[0]);
is a function with only one parameter.
OK, I know it sounds weird but I need to make a function that will receive two parameters the first one is a string and the second an array (containing strings).
This function will then call sprintf. My first parameter will be $format and my array will correspond to the various $args.
How can I achieve this (if possible)?
Thanks!
Well you want the vsprintf() function.
Like Orbling answered, for this particular case you need vsprintf.
But, in a generic case, to call a function with variable number of parameters, you can use func_get_args() inside the function which you desire to accept multiple (any number of variable arguments). This function (when called inside your function) returns an array containing all the parameters passed while calling your function.
In short, what I want is a kind of export() function (but not export()), it creates new variables in symbol table and returns the number of created vars.
I'm trying to figure out if it is possible to declare a function
function foo($bar, $baz)
{
var_dump(func_get_args());
}
And after that pass an array so that each value of array would represent param.
Just wondering if it is possible (seems that is not).
I need this for dynamic loading, so number of arguments, size of array may vary - please dont offer to pass it as
foo($arr['bar']);
and so on.
Again, ideal thing solution will look like
foo(array('foo'=>'1', 'bar'=>'2', ..., 'zzz'=>64));
for declaration
function foo($foo, $bar, ..., $zzz) {}
As far as I rememeber in some dynamical languages lists may behave like that (or maybe I'm wrong).
(I want to create dynamically parametrized methods in class and built-in mechanism of controlling functions arguments number, default value and so on is quite good for this, so I could get rid of array params and func_get_args and func_get_num calls in the method body).
Thanks in advance.
You're looking for call_user_func_array
example:
function foo($bar, $baz)
{
return call_user_func_array('beepboop',func_get_args());
}
function beepboop($bar, $baz){
print($bar.' '.$baz);
}
foo('this','works');
//outputs: this works
I don't know about the speed but you could use ReflectionFunction::getParameters() to get what name you gave the parameters, combined with call_user_func_array() to call the function. ReflectionFunction::invokeArgs() could be used as well for invoking.
What about just passing in an associative array and acting on that array?
How about using extract()?
<?php
/* Suppose that $var_array is an array returned from
wddx_deserialize */
$size = "large";
$var_array = array("color" => "blue",
"size" => "medium",
"shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");
echo "$color, $size, $shape, $wddx_size\n";
?>
(Code taken from PHP example)