如何实现可以接受不同数量参数的php构造函数?
发布时间:2020-12-13 18:23:51 所属栏目:PHP教程 来源:网络整理
导读:如何实现可以接受不同数量参数的php构造函数? 喜欢 class Person { function __construct() { // some fancy implementation } } $a = new Person('John');$b = new Person('Jane','Doe');$c = new Person('John','Doe','25'); 在php中实现这个的最佳方法是
如何实现可以接受不同数量参数的php构造函数?
喜欢 class Person { function __construct() { // some fancy implementation } } $a = new Person('John'); $b = new Person('Jane','Doe'); $c = new Person('John','Doe','25'); 在php中实现这个的最佳方法是什么? 谢谢,
一种解决方案是使用默认值:
public 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指出了第三个选项:
编辑:粘贴在这里我能从original answer由tandu(现在:爆炸药丸)检索. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |