Fake function/method overloading in PHP

Ever needed to call the same function with different number of parameters? Easy right, just use default values:

  1. function tryMe($param1, $param2 = NULL, $param3 = NULL) {}

But what if you want to make the first parameter optional?
Here’s a simple technique for doing so it in a transparent way.

  1. function tryMe($param1, $param2 = NULL, $param3 = NULL) {
  2.   $args = array_pad(func_get_args(), 3, null);
  3.   switch (func_num_args()) {
  4.     case 2:
  5.       list($param2, $param3,      $param1) = $args;
  6.       break;
  7.     case 1:
  8.       list($param3,      $param2, $param1) = $args;
  9.       break;
  10.   }
  11.   print "param1: $param1, param2: $param2, param3: $param3".PHP_EOL;
  12. }
  13.  
  14. print tryMe(1,2,3);
  15. print tryMe(1,2);
  16. print tryMe(1);

When you run the code you get:

C:\>php -f test.php
param1: 1, param2: 2, param3: 3
param1: , param2: 1, param3: 2
param1: , param2: , param3: 1

The point of this technique is to make it obvious that you’re trying to reassign the parameters and do it with as few lines as possible.

Leave a Reply