How to implement php constructor that can accept different number of parameters?
How to implement php constructor that can accept different n开发者_JAVA技巧umber 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
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).
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
精彩评论