jump to navigation

Multiple Constructor in PHP January 31, 2008

Posted by ordinarywebguy in PHP, PHP 5, Programming.
trackback

How?

See code:

class MultipleConstructor {

private $info = ”;

function __construct() {
$argv = func_get_args();
switch( func_num_args() )
{
default:
case 1:
self::__construct1($argv[0]);
break;
case 2:
self::__construct2( $argv[0], $argv[1] );
break;
}
}

function __construct1($value) {
$this->info = $value;
}

function __construct2($value, $value2) {
$this->info = $value . ” ” . $value2;
}

function get() {
return $this->info;
}
}

$a = new MultipleConstructor(‘Value 1′);
echo $a->get();

$b = new MultipleConstructor(‘Value 1′, ‘Value 2′);
echo $b->get();

Viola!!!

Comments»

1. Andrew - June 10, 2008

Thanks, it was very helpful!

P.S. I now hate PHP even more ;)

2. OJ - August 14, 2008

You code in PHP, you deserve to suffer code like this :)

3. CL - March 4, 2009

How about something like this, which might be slightly less ulgy?:

function __construct() {
$argv = func_get_args();
$constructor = ‘__construct’ . $argv.length;
$constructor($argv); // indirectly call correct function
}

function __construct1($argv) {
$arg1 = $argv[0];

}

function __construct2($argv) {
$arg1 = $argv[0];
$arg2 = $argv[1];

}

I haven’t tested it out yet, but I think that would work. Keep in mind that although I’m a developer, I’m relatively new to PHP.

4. CL - March 4, 2009

Well, that seemed to work with a little tweaking. Note that there’s a bit of weirdness in dealing with the one-argument constructor args. I’m not sure why, but if you just use $args[0], you get “Array”.

The code:

function __construct()
{
echo ‘In default constructor…’;
$argv = func_get_args();
$constructor = ‘construct’ . count($argv);
$this->$constructor($argv); // call correct constructor
echo $this->toString();
}

private function construct1($args)
{
echo ‘In construct1()…’;
$this->make = $args[0][0];
}

private function construct2($args)
{
echo ‘In construct1()…’;
$this->make = $args[0];
$this->model = $args[1];
}

private function construct3($args)
{
echo ‘In construct3()…’;
$this->make = $args[0];
$this->model = $args[1];
$this->color = $args[2];
}

5. nico - May 10, 2009

This hack is fine, but will fail if you want multiple constructor with the same number of parameters…

A much cleaner way to do it is the one described here:

http://www.alfonsojimenez.com/computers/multiple-constructors-in-php