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.
-- 
Lamont Peterson <[email protected]>
Founder [ http://blog.OpenBrainstem.net/peregrine/ ]
GPG Key fingerprint: 0E35 93C5 4249 49F0 EC7B  4DDD BE46 4732 6460 CCB5
  ___                   ____            _           _
 / _ \ _ __   ___ _ __ | __ ) _ __ __ _(_)_ __  ___| |_ ___ _ __ ___
| | | | '_ \ / _ \ '_ \|  _ \| '__/ _` | | '_ \/ __| __/ _ \ '_ ` _ \
| |_| | |_) |  __/ | | | |_) | | | (_| | | | | \__ \ ||  __/ | | | | |
 \___/| .__/ \___|_| |_|____/|_|  \__,_|_|_| |_|___/\__\___|_| |_| |_|
      |_|               Intelligent Open Source Software Engineering
                              [ http://www.OpenBrainstem.net/ ]
_______________________________________________

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

Reply via email to