Dynamic PHP Function Arguments

PHP functions are great methods for optimizing your site. The real power of PHP comes from its functions.There are more than 700 built-in functions, and endless ones that you can make yourself. But a good think to know about is arguments. And more specifically dynamic arguments.

Sometimes, depending on a function, the number of arguments will change for every use. Instead of having to write new functions each time, you can use the PHP function func_get_args() to compile all the parent functions arguments into an array.

Here’s the basic usage:

1
2
3
4
function awesome() {
  $args = func_get_args();
  // function continues...
}

Pretty simply enough. A good real life example would be the following function that handles mysql queries:

1
$result = _query("SELECT * FROM table WHERE name = '%s' AND client = '%s'", $_POST['name'], $_POST['client']);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
function _query() {
  include('connect.php'); // contains code to connect to database
 
  $args = func_get_args();
  $query = array_shift($args); // 1st argument is the actual query.
  if ($args) $query = vsprintf($query, escapeSQL($args));
 
  if ($result = mysql_query($query)) {
    if (mysql_num_rows($result) > 0) {
      while ($row = mysql_fetch_assoc($result)) $out[] = $row;
    } else {
      $out = array("error", 'no results', $query);
    }
    return $out;
  } else {
    return array("error", mysql_error(), $query);
  }
}
 
function escapeSQL($str) {
  include('connect.php');
  if (is_array($str)) {
    foreach ($str as $key => $value) {
      $str[$key] = (is_array($value)) ? escapeSQL($value) : mysql_real_escape_string(stripslashes($value));
    }
  } else {
    $str = mysql_real_escape_string(stripslashes($str));
  }
  return $str;
}

And there you have it! There is also two other functions in relation to a functions arguments: func_get_arg() and func_num_args. There former is used to retrieve individual arguments based on their index value, and the later simply returns the number of arguments.

1
2
3
4
5
6
7
8
9
10
11
12
13
func_get_arg(2);
func_num_args();
 
// Example
function test() {
  echo 'Argument 1 = '.func_get_arg(1);
  echo 'Argument Count = '.func_num_args();
}
 
test('1st Argument', '2nd Argument', '3rd Argument', '4th Argument');
 
// Argument 1 = 2nd Argument
// Argument Count = 4

There are countless ways you can apply the function, so see what you can come up with! :)

October 8th, 2009 | PHP

Leave a Reply

Name:
Email:
Website:
Message:
SUBMIT