Finally, passing arguments by name in PHP!

This is absolutely not paddle related but yesterday at work (new year, new job!) I figured out in php how to pass arguments to a function by name rather than in the classical order. In Perl this is quite common, see also and . As you can see, these articles are quite old and in a previous life I have used passing arguments by name quite happily.

As php is somewhat related to Perl I was hoping I could find a similar method, being a php noob at the time. But alas, no one of the php “seniors” I was working with at that time had a clue what I was talking about. The Zend php certification book literally stated: “what you want are variable length argument lists”. Well, in a sense I do but I certainly do not want to have to count my arguments etc. To be honest, the solutions given in the certification book were not always an example of good practice to me.

So, I was quite unhappy about this part of php but yesterday I figured out this very nice line of code:

function testIt($var1='silent1', $var2='silent2', $var3='silent3', $var4='silent4')
        extract(array_pop(func_get_args()),EXTR_OVERWRITE); // this is it!

        echo 'var1: ' . $var1 . '<br/>var2: ' . $var2 . '<br/>var3: ' . $var3.'<br/>Var4: ' . $var4.'<br/>';

   $pAr = array('var1' => 'beep1', 'var3'=>'beep3');
   echo 'Start...<br/>';
   echo 'Done...<br/>';

 The result of this is:

var1: beep1
var2: silent2
var3: beep3
Var4: silent4
The code above is obviously very simple and needs some error checking before it is used in the real world but I guess the idea is pretty straightforward. The best bit is: it even used the standard way of defining default values in php.
So with some minor modifications (mainly some robust checking) it is even possible to use it in existing code and still keep the code backwards compatible!

If this was of any use to you, please use it and perfect it. It's all public domain you know..

Comments are closed.