Variadic Function

Few years ago, I was introduced to this PHP function func_get_args() by my senior while reading his code (can't remember what or why he used it for). This function allows you to create a function that can take multiple arguments and no argument list declaration in your function signature. Code shown below is an example of a helper function to find the maximum value from a set of number.
function max() {
   $max = -PHP_INT_MAX;
   foreach(func_get_args() as $arg) {
      if ($arg > $max) {
          $max = $arg;
      }
   }
   return $max;
}

echo max(1,5,7,3);
7

Why I brought this up ? I didn't realize that the term "variadic function" is used to describe function that support multiple arguments until I read the Request For Comment (RFC) on the proposal of a new syntax for variadic function for PHP. Historically, variadic function is an old concept that long implemented in C programming language, especially for printf() and scanf() function. Not surprisingly, these two functions also existed in PHP , since it's a C-based programming language.

Back to the RPC. Reading through the discussion in Reddit and the RFC itself. I think is a good idea since we can now enforce type hints and enforcing consistency on interface. However, a feature that is nice to have but only useful for those framework or library writer and not mere library consumer like us.

No comments:

Post a Comment