Jan 29, 2011

Optional Function Arguments

Today's a two-for-one post day. :)

I just read this article, which I must have missed in the mess of RSS feeds I subscribe to. It's an interesting tutorial, definitely worth a read. But what interests me so much is the first part - Passing optional or any number of function arguments.

Now PHP has a huge range of functions, and there are no doubt some you may not know about. A lot of my functions have optional arguments, sometimes written like so:
function foo( $argument = FALSE )
{
  if ($argument)
  {
    //Do something
  }
  else {
    //Do something else
  }
}

Anyway, I had never thought of accepting any number of parameters to a function using func_get_args(). And there are plenty of uses for a function like that. The php.net manual has some examples that illustrate some uses. But I can think of plenty more. For my PBBG for example, I might accept lots of different params in a function that points a user action to it's respective class.

It might look something like this:
function foo()
{
  $action = func_get_args();
  
  //The first argument would always
  //be the action's name
  switch($action[0])
  {
    case 'attack':
      //The second argument would
      //be the players attack stat in this case
      battle::attack($action[1]);
      break;
    case 'retreat':
      //Maybe speed in this case
      battle::retreat($action[1]);
      break;
    case 'cast':
      //And so on and so forth...
      battle::cast($action[1], $action[2]);
      break;
   }
}

This is obviously a simplistic example, but with some extra code this could add a layer of security to my application.

Here's another example that can be used to sanitize queries:
function mysql_safe($q) {
    $x = array_shift(func_get_args());
    return vsprintf(preg_replace('/%([1-9]):(d|s)/','%$1$$2',$q),
    array_map('mysql_escape_string',$x));
}

Comment if you have an interesting use for this function, or if you have a function you'd like me to do a post on. Happy coding!

No comments:

Post a Comment