Re: func_get_args as a hash? (faster constructors)

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Tuesday 28 November 2006 20:09, Jochem Maas wrote:
> Kelly Jones wrote:
> > If I define a function like this:
> >
> > function foo ($x, $y, $z) {}
> >
> > and then call: foo(1,2,"bar");
> >
> > is there a function I can call inside foo() that yields this hash:
> >
> > {"x" => 1, "y" => 2, "z" => "bar"}
> >
> > In other words, gives me the values *and names* of the arguments to foo?
> >
> > func_get_args just yields the values.
> >
> > Having this function would make writing constuctors easier.
> >
> > The normal way:
> >
> > fuction ClassName ($x, $y, $z) {
> >   $this->x = $x;
> >   $this->y = $y;
> >   $this->z = $z;
> > }
> >
> > could be replaced with:
> >
> > function ClassName ($x, $y, $z) {
> >   foreach (magic_function_i_want() as $key=>$val) {
> >      $this->$key =$val;
> >   }

In the Javascript world, it's becoming more common to pass a key/value object 
(what in the PHP world we call an associative array) as a single parameter.  
That gives you keyed values, and no order-requirements if you want default 
values for the first 5 parameters and just one difference for the last one.  
To wit:

function foo($params) {
  if (!isset($params['bar']) $params['bar'] = 'a';
  if (!isset($params['baz']) $params['baz'] = 'b';
...
}

Or for a constructor, you'd do something like this:

class Foo {
  private $bar = 'a';
  private $baz = 'b';

  function __construct($params) {
    foreach ($params as $key => $value) {
      $this->$key = $value;
    }
  }
}

The down side of course is that calling the function/object has a different 
syntax then.  Nothing is free. :-)

-- 
Larry Garfield			AIM: LOLG42
larry@xxxxxxxxxxxxxxxx		ICQ: 6817012

"If nature has made any one thing less susceptible than all others of 
exclusive property, it is the action of the thinking power called an idea, 
which an individual may exclusively possess as long as he keeps it to 
himself; but the moment it is divulged, it forces itself into the possession 
of every one, and the receiver cannot dispossess himself of it."  -- Thomas 
Jefferson

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux