...

View Full Version : Elegant way of handling nested constructors with variable argument lists?



mlse
08-17-2007, 12:58 PM
Hi all,

I wonder if there is an elegant (i.e. syntactic way) of passing variable argument lists between nested constructors (or any function), for that matter.

The problem which arises is as follows:




class mybase
{
public function __construct()
{
$argc = func_num_args();
$argv = func_get_args();

//Do something here with argv and argc.
}
}

class myderived extends mybase
{
public function __construct()
{
parent::__construct(); //Here is the problem!

//Do something here.
}
}


I can think of various solutions (I prefer to call them hacks!), the most obvious of which is to write a protected function to be called from mybase::__construct() which wraps the function args into an array anyway (so that they can be wrapped into an array and passed directly to that underlying function in the constructor of the derived class), however I would put that particular solution into the category of "ugly"!

I wonder if there is a mechanism that is built into PHP5 for doing this ... in C, for example, using the stdarg library (in a posix environment) forces the handling of variable argument lists using a separate language construct, which can be recursively passed to functions (a neat solution!).

Mike :)

GJay
08-17-2007, 02:25 PM
you could do something like:


class derived extends base {
public function __construct() {
$args = func_get_args();
call_user_func_array(array(parent,'__construct'),$args);
}

}


but it's still not particularly nice. What's the use-case for variable arguments to a constructor that can't be handled with optionals?

mlse
08-17-2007, 08:56 PM
None really! I've just gotten used to writing C for so long that I prefer variable arg lists to optionals! Also, I have one particular base class which I'd like to be able to initialise with an arbitrary number of arguments.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum