View Full Version : argument list in an array
NancyJ
04-13-2008, 10:20 PM
Ok say I have a function foo
function foo($arg1='', $arg2='', $arg3='')
{
}
But the data I need to pass into the function are in a numerical array. Now in this situation I could just do
foo($array[0], $array[1], $array[2});
But what if I have another function bar that takes 5 parameters and what if I don't know how many elements will be in the array - I can count them and I can count the number of arguments a function needs, BUT how do I then pass them into the function (which fwiw is also variable)... without using eval.
oesxyl
04-13-2008, 10:44 PM
Ok say I have a function foo
function foo($arg1='', $arg2='', $arg3='')
{
}
But the data I need to pass into the function are in a numerical array. Now in this situation I could just do
foo($array[0], $array[1], $array[2});
But what if I have another function bar that takes 5 parameters and what if I don't know how many elements will be in the array - I can count them and I can count the number of arguments a function needs, BUT how do I then pass them into the function (which fwiw is also variable)... without using eval.
it's not clear to me, I mean the problem is to general to talk about a solution, or I don't understand what you want.
I guess some answer you could find here:
http://www.php.net/manual/en/book.funchand.php
seems stupid but could be usefull if you don't already know about, :)
http://www.php.net/manual/en/language.variables.variable.php
http://www.php.net/manual/en/functions.variable-functions.php
You need something like that?
<?php
function f1($v){
echo $v;
}
function f2($a){
$f = $a[0];
$f($a[1]);
}
$a = array("f1", "hello world");
f2($a);
?>
I hope that help.
best regards
NancyJ
04-13-2008, 10:55 PM
call_user_func_array does exactly what I want except that the function is actually a method of an object.
oesxyl
04-13-2008, 11:12 PM
call_user_func_array does exactly what I want except that the function is actually a method of an object.
I guess you can use global an a wrapper:
$myobj = new MyClass();
function cufa($par){
global $myobj;
$myobj->mymeth($par);
}
$result = call_user_func_array("cufa", $param);
I'm not sure if you really need to use global, but I guess you need, make some test.
I'm idiot some times, :)
You can use methods as callback function:
http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback
regards
NancyJ
04-13-2008, 11:18 PM
You know, I thought about clicking on the callback types link but then I didn't for some reason. Excellent
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.