Re: func_get_args as a hash? (faster constructors)
| From: | Jochem Maas | Date: | Wed, 29 Nov 2006 02:09:20 +0000 |
| Subject: | Re: func_get_args as a hash? (faster constructors) | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-245258@lists.php.net to get a copy of this message | ||
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;
> }
which is slower.
what might be nice is a special function modifier (just thinking out loud):
autoargs function __construct($x, $y, $z) {
$this->foo = 'bar';
}
which would be equivalent to:
function __construct($x, $y, $z) {
$this->x = $x;
$this->y = $y;
$this->z = $z;
$this->foo = 'bar';
}
but it's such a simplistic idea that its probably
not worthy - in practice objects don't often taken that many args
and more often than not you [should be] doing some sanitation
of the args.
> }
>
> Obviously, it's more of a savings when you have a large number of
> parameters.
you might consider a meta class concept - write classes that are used as configurations
add/update boiler-plate init code for classes.
MetaCls () {
$args = array('x', 'y', 'z');
}
--
php run_meta_generation_routine.php -c Cls
--
Cls {
/* added by run_meta_generation_routine.php */
function __construct($x, $y, $z) {
$this->x = $x;
$this->y = $y;
$this->z = $z;
}
}
>