如何实现可以接受不同数量参数的PHP构造函数?
喜欢
class Person { function __construct() { // some fancy implementation } } $a = new Person('John'); $b = new Person('Jane','Doe'); $c = new Person('John','Doe','25');
谢谢,
米洛
一种解决方案是使用默认值:
原文链接:https://www.f2er.com/php/135667.htmlpublic function __construct($name,$lastname = null,$age = 25) { $this->name = $name; if ($lastname !== null) { $this->lastname = $lastname; } if ($age !== null) { $this->age = $age; } }
第二个是接受数组,关联数组或对象(关于关联数组的例子):
public function __construct($params = array()) { foreach ($params as $key => $value) { $this->{$key} = $value; } }
但在第二种情况下,它应该像这样传递:
$x = new Person(array('name' => 'John'));
tandu指出了第三个选项:
Constructor arguments work just like any other function’s arguments. Simply specify defaults PHP.net/manual/en/… or use
func_get_args()
.
编辑:粘贴在这里我能从original answer由tandu(现在:爆炸药丸)检索.