function do_something_awesome($params = array()) {
    $default = array(
        'a' => 'a',
        'b' => 'b',
    );
    $params = array_merge($default, $params);

    ....

}

Lamont Peterson wrote:
On Saturday 10 January 2009 08:14:20 am Walt Haas wrote:
The usual approach would be to write

function do_something_awesome( $params = array() )
{
    if ( array_key_exists( 'a', $params ) ) {
        $param_a = $params( 'a' );
    } else {
        $param_a = 'a';
    }
    if ( array_key_exists( 'b', $params ) ) {
        $param_b = $params( 'b' );
    } else {
        $param_b = 'b';
    }
}

Then you can write calls like

do_something_awesome( );
do_something_awesome( array( 'a' => 'foo' ) );
do_something_awesome( array( 'b' => 'bar' ) );
do_something_awesome( array( 'a' => 'foo', 'b' => 'bar' ) );

Here's a variation on Walt's approach:

function do_something_awesome ($parameters = array ())
{
   $default_parameters = array (
      'a' => 'a',
      'b' => 'b');
   foreach ($parameters as $parameter => $value)
   {
      $default_parameters[$parameter] = $value;
   }
   $parameters = $default_parameters;
   unset ($default_parameters;

   // Do awesome stuff.
}

I'll you figure out why I wrote this example to loop through the passed in parameters instead of the defaults :) .

Another thing you could do is to create a process_passed_parameters_array () function. Basically, take the foreach loop, put it in the function and have it take the list of defaults and the parameters that were passed in:

function process_passed_parameters_array ($defaults, $parameters)
{
   foreach ($parameters as $parameter => $value)
   {
      if (array_key_exists ($parameter, $defaults)
      {
         $defaults[$parameter] = $value;
      }
      else
      {
         // We don't want to allow parameters that are
         // not in the defaults list.  You could extend
         // this code to throw an exception, if preferred.
      }
   }
   return $defaults;
}

Then, you can call it:

function do_something_awesome ($parameters = array ())
{
$parameters = process_passed_parameters_array (array ('a' => 'a', 'b' => 'b', 'c' => ''), $parameters)

   // Do awesome stuff.
}

This could easily be extended to require some parameters.

Still, I also like the func_num_args () approach for some situations.


------------------------------------------------------------------------


_______________________________________________

UPHPU mailing list
[email protected]
http://uphpu.org/mailman/listinfo/uphpu
IRC: #uphpu on irc.freenode.net


_______________________________________________

UPHPU mailing list
[email protected]
http://uphpu.org/mailman/listinfo/uphpu
IRC: #uphpu on irc.freenode.net

Reply via email to