8

How to implement php constructor that can accept different number of parameters?

Like

class Person {
    function __construct() { 
        // some fancy implementation
    } 
} 

$a = new Person('John');
$b = new Person('Jane', 'Doe');
$c = new Person('John', 'Doe', '25');

What is the best way to implement this in php?

Thanks, Milo

2
  • Constructor arguments work just like any other function's arguments. Simply specify defaults php.net/manual/en/… or use func_get_args() Commented May 13, 2011 at 1:08
  • Constructor arguments work just like any other function's arguments. Simply specify defaults php.net/manual/en/… or use func_get_args() Commented May 13, 2011 at 1:10

2 Answers 2

12

One solution is to use defaults:

public function __construct($name, $lastname = null, $age = 25) {
    $this->name = $name;
    if ($lastname !== null) {
        $this->lastname = $lastname;
    }
    if ($age !== null) {
        $this->age = $age;
    }
}

The second one is to accept array, associative array or object (example about associative array):

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

But in the second case it should be passed like this:

$x = new Person(array('name' => 'John'));

The third option has been pointed by tandu:

Constructor arguments work just like any other function's arguments. Simply specify defaults php.net/manual/en/… or use func_get_args().

EDIT: Pasted here what I was able to retrieve from original answer by tandu (now: Explosion Pills).

Sign up to request clarification or add additional context in comments.

2 Comments

@Tadeck, your link to tandu now goes to the Explosion Pills developer page, not clear where the answer page is from there. If you recall what the 3rd answer is, can you paste it here in an update to your answer?
@JesseChisholm: This is the same user (link is based on user ID, this user simply changed nickname). And yes, the third answer is still even visible to me, but removed by moderator (link to is is, if you are able to see: stackoverflow.com/a/5986259/548696). Adding content of his/her answer to mine.
3

Updated Answer:

echo '<pre>';

// option 1 - combination of both tadeck's and my previous answer

class foo {
    function __construct() {
        $arg_names = array('firstname', 'lastname', 'age');
        $arg_list = func_get_args();
        for ($i = 0; $i < func_num_args(); $i++) {
            $this->{$arg_names[$i]} = $arg_list[$i];
        }
    }
}

$foo = new foo('John', 'Doe', 25);

print_r($foo);

// option 2 - by default, PHP lets you set arbitrary properties in objects, even
// if their classes don't have that property defined - negating the need for __set()

// you will need to set properties one by one however, rather than passing them as
// parameters

class bar {
}

$bar = new bar();
$bar->firstname = 'John';
$bar->lastname = 'Doe';
$bar->age = 25;

print_r($bar);

Result:

foo Object
(
    [firstname] => John
    [lastname] => Doe
    [age] => 25
)
bar Object
(
    [firstname] => John
    [lastname] => Doe
    [age] => 25
)

Previous Answer:

<?php

class Person {
    function __construct() {
        $arg_list = func_get_args();
        echo '<p>';
        for ($i = 0; $i < func_num_args(); $i++) {
            echo 'Argument '.$i.' is: '.$arg_list[$i].'<br />', "\n";
        }
    }
}

$a = new Person('John');
$b = new Person('Jane', 'Doe');
$c = new Person('John', 'Doe', '25');

?>

Result:

Argument 0 is: John

Argument 0 is: Jane
Argument 1 is: Doe

Argument 0 is: John
Argument 1 is: Doe
Argument 2 is: 25

3 Comments

Another option is to use overloading in PHP (_set)
can you give some details about how you would use _set() overloading to achieve similar effect?
@Tadeck: i've refactored my answer, though __set() isn't really necessary

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.