I'm working on a CMS, and I'm looking for a way to convert a list of function arguments, into an array. For example:
function testfunction($param1, $param2){
$string = "Param1: $param1 Param2: $param2";
return $string;
}
$funcname = 'testfunction';
$params = "'this is, parameter 1', 'this is parameter2'";
//This doesnt work, sends both parameters as the first, dont know why.
echo call_user_func($funcname, $params);
//So I want to split the parameter list:
$paramsarray = preg_split('%Complex Regex%', $params);
//And call thusly:
echo call_user_func_array($funcname, $paramsarray);
I dont know what kind of regex to use here.... I could just explode by ',' but that would explode all commas contained in strings, arrays etc... So I need a regex to do this, I'm ok with regexes, but it seems like there would be a lot of rules in this.
I guess if you really want to start from a string (instead of an array like others suggested), you could do:
In PHP 5.3:
$params = "'this is, parameter 1', 'this is parameter2'";
$paramsarray = str_getcsv($params, ',', "'");
In PHP 5.1/5.2:
$fp = fopen('php://temp', 'w+');
fwrite($fp, $params);
fseek($fp, 0);
$paramsarray = fgetcsv($fp, 0, ',', "'");
print_r($paramsarray);
...and get:
Array
(
[0] => this is, parameter 1
[1] => this is parameter2
)
...then use call_user_func_array
.
If you want to use more complex types (e.g.: arrays or objects), that'll be a real challenge. You'll probably have to use the Tokenizer.
Maybe you could just use func_get_args for this?
Also, call_user_func I believe should be called like this:
call_user_func('functionName', $param1, $param2);
Try maybe using call_user_func_array
instead.
$params
is (in your case) a single variable, that contains a single value of type string
. Its not an array or any other complex type. I assume, that you don't even need your %Complex Regex%
.
$funcname = 'testfunction';
$params = "'this is, parameter 1', 'this is parameter2'";
foreach ($params as &$param) $param = trim($param, "'
\t");
echo call_user_func_array($funcname, $params);
Sounds like you want call_user_func_array instead.
$params = array('this is, parameter 1', 'this is parameter2');
$funcname = 'testfunction';
echo call_user_func_array($funcname, $params);