Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How-To Pass an array to a function which uses func_get_args to retrieve parameter

Tags:

php

I am programming to an API method which accepts a variable number of arguments. The API method (see below) uses func_get_args. I am wrapping the API, and would like to be able to pass an associative array instead of passing the keys/values of the array as parameters; i.e. filter(key1,value1,key2,value2 ...)

I have source code access to the API, but unfortunately I can not change the source.
I have looked at call_user_func_array, which I believe should/will pass an array as a set of arguments (though not an associative array). filter is a method of an object - I don't know how to pass a method as a callback. I also don't know if there is a clean way to wrap this API. Any and all help is appreciated.

<?php

public function &filter() {
        $filter = new QueryFilter($this->queryhandler, $this);
        $args = func_get_args();
        $filter->applyFilter($this->getFilters($args));
        return $filter;
    }
like image 432
Binary Alchemist Avatar asked Oct 05 '22 21:10

Binary Alchemist


1 Answers

You could have a wrapper that takes an array and "flattens" the keys and values:

function wrapper(array $params) {
    $flat = array();
    foreach ($params as $k => $v) {
        $flat[] = $k;
        $flat[] = $v;
    }

    return call_user_func_array('filter', $flat);
}

The above assumes that filter is a free function, which in your case isn't true. To specify a method as a callback, use the syntax array($object, 'filter') with call_user_func_array to call the method filter on $object.

like image 85
Jon Avatar answered Oct 10 '22 03:10

Jon