Is it possible to create overload chains in PHP?

This is a compiled example, it becomes much more useful when there are many parameters.

This will allow the subscriber to use either new Person("Jim", 1950, 10, 2) or new Person("Jim", datetimeobj) . I know about advanced options, this is not what I am looking for here.

In C #, I can do:

 public Person(string name, int birthyear, int birthmonth, int birthday) :this(name, new DateTime(birthyear, birthmonth, birthday)){ } public Person(string name, DateTime birthdate) { this.name = name; this.birthdate = birthdate; } 

Is it possible to do something like this in PHP? Sort of:

 function __construct($name, $birthyear, $birthmonth, $birthday) { $date = new DateTime("{$birthyear}\\{$birthmonth}\\{$birthyear}"); __construct($name, $date); } function __construct($name, $birthdate) { $this->name = $name; $this->birthdate = $birthdate; } 

If this is not possible, what is a good alternative?

+4
source share
2 answers

For this I will use named / alternative constructors / factories or whatever you want to name:

 class Foo { ... public function __construct($foo, DateTime $bar) { ... } public static function fromYmd($foo, $year, $month, $day) { return new self($foo, new DateTime("$year-$month-$day")); } } $foo1 = new Foo('foo', $dateTimeObject); $foo2 = Foo::fromYmd('foo', 2012, 2, 25); 

There must be one canonical constructor, but you can have as many alternative constructors as handy wrappers, which are all canonical. Or you can set alternative values ​​in these alternative constructors, which you usually don’t set in the usual:

 class Foo { protected $bar = 'default'; public static function withBar($bar) { $foo = new self; $foo->bar = $bar; return $foo; } } 
+6
source

This is not exactly the same, but you can manipulate the number of arguments in the constructor, read them, or check their types and call the corresponding functions. As an example:

 class MultipleConstructor { function __construct() { $args = func_get_args(); $construct = '__construct' . func_num_args(); if (method_exists($this, $construct)) call_user_func_array(array($this, $construct), $args); } private function __construct1($var1) { echo 'Constructor with 1 argument: ' . $var1; } private function __construct2($var1, $var2) { echo 'Constructor with 2 arguments: ' . $var1 . ' and ' . $var2; } } $pt = new MultipleConstructor(1); $pt = new MultipleConstructor(2,3); 
+1
source

Source: https://habr.com/ru/post/1398332/


All Articles