如何实现可以接受不同数量参数的php构造函数?

前端之家收集整理的这篇文章主要介绍了如何实现可以接受不同数量参数的php构造函数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何实现可以接受不同数量参数的PHP构造函数

喜欢

  1. class Person {
  2. function __construct() {
  3. // some fancy implementation
  4. }
  5. }
  6.  
  7. $a = new Person('John');
  8. $b = new Person('Jane','Doe');
  9. $c = new Person('John','Doe','25');

PHP中实现这个的最佳方法是什么?

谢谢,
米洛

一种解决方案是使用默认值:
  1. public function __construct($name,$lastname = null,$age = 25) {
  2. $this->name = $name;
  3. if ($lastname !== null) {
  4. $this->lastname = $lastname;
  5. }
  6. if ($age !== null) {
  7. $this->age = $age;
  8. }
  9. }

第二个是接受数组,关联数组或对象(关于关联数组的例子):

  1. public function __construct($params = array()) {
  2. foreach ($params as $key => $value) {
  3. $this->{$key} = $value;
  4. }
  5. }

但在第二种情况下,它应该像这样传递:

  1. $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(现在:爆炸药丸)检索.

猜你在找的PHP相关文章