[phpclass] dinamicParams – Calling function with named params

by Gabi Solomon

A lot of time while developing a function or a method of a class you need to specify 1, 2 or 3 parameters as inputs for that function or method. But usually as you develop further you might end-up in the situation where you would want to add a new parameter to your function.

And so you might have coded a function that has 5 or more parameters, and although it works fine, eventually you will want to call that function and leave the first 4 parameters with the default value and only change the last one. I ended up here a lot of times, and normally in php there is nothing you can do.

A workaround would be to specify the params as a single array variable, but that is just making you write more code and it looks really bad ( at least in my opinion).

Well today i found a new method of doing this in php5 with the help of the Reflection API that is offer in php5. I will not get into to much details about what it does, you can read that in the documentation, basicly it provides a way to reverse-engineer classes, interfaces, functions and methods.

So i wrote a simple class that is going to solve that problem.

With the help of the Reflection API from php5 the class will allow you to call function and methods by providing the parameters as an array specifying names and values even if the original function or methods receives them in the normal fashion.

But enough talk, heres the example.

class news {

function fetch ( $id, $page = 0, $items_pp = 10, $order_by = 'date', $method = 'desc') {
echo "
id: $id,
page: $page,
items_pp: $items_pp,
order_by: $order_by,
method: $method


$news = new news();
$dinamicParams = new dinamicParams();

$dinamicParams->call(array($news, ‘fetch’), array(‘order_by’ => ‘name’));

This will output :

id: , page: 0, items_pp: 10, order_by: name, method: desc

This class is based on this implementation of the reflection API.
It is available on phpclasses can be downloaded here