hoy*_*omi 7 php constructor multiple-constructors
如何实现可以接受不同数量参数的php构造函数?
喜欢
class Person {
function __construct() {
// some fancy implementation
}
}
$a = new Person('John');
$b = new Person('Jane', 'Doe');
$c = new Person('John', 'Doe', '25');
Run Code Online (Sandbox Code Playgroud)
在php中实现这个的最佳方法是什么?
谢谢,米洛
Tad*_*eck 10
一种解决方案是使用默认值:
public function __construct($name, $lastname = null, $age = 25) {
$this->name = $name;
if ($lastname !== null) {
$this->lastname = $lastname;
}
if ($age !== null) {
$this->age = $age;
}
}
Run Code Online (Sandbox Code Playgroud)
第二个是接受数组,关联数组或对象(关于关联数组的例子):
public function __construct($params = array()) {
foreach ($params as $key => $value) {
$this->{$key} = $value;
}
}
Run Code Online (Sandbox Code Playgroud)
但在第二种情况下,它应该像这样传递:
$x = new Person(array('name' => 'John'));
Run Code Online (Sandbox Code Playgroud)
tandu指出了第三种选择:
构造函数参数的工作方式与任何其他函数的参数一样.只需指定默认值php.net/manual/en/...或使用
func_get_args().
编辑:粘贴在这里我能够从tandu(现在:爆炸药丸)的原始答案中检索.