If you are really interested in the ability to control with a dynamic number of parameters, then you can use either this way:
class A { public function __construct(...$args) { switch (count($args)) { case 1: //use $args[0]; break; case 2: //use $args[0], $args[1]; break; case 3: //use $args[0], $args[1], $args[2]; break; } } } $a = new A('color', 'qwerty', 'color');
or, as already given an example, transfer parameters in the array:
class B { public function __construct($args) { switch (count($args)) { case 1: //use $args[0]; break; case 2: //use $args[0], $args[1]; break; case 3: //use $args[0], $args[1], $args[2]; break; } } } $b = new B(['123', '234']); class C { public function __construct($args) { if (!emtpy($args['color'])) { if (!empty($args['qwerty'])) { if (!empty($args['name'])) { //use [color, qwerty, name] } else { //use [color, qwerty] } } else { //use only [color] } } } } $c = new C(['color' => '123', 'qwerty' => '234']);
, or, if you want dynamic-predynamic at all, then something like this :
class D { public function three($args) { print $args['color'].', '.$args['name']; } public function __construct($args) { $constructors = [ 'one' => ['color'], 'two' => ['color', 'qwerty'], 'three' => ['name', 'color'], 'four' => ['color', 'qwerty', 'name'] ]; foreach ($constructors as $key => $value) { sort($constructors[$key]); } $keys = array_keys($args); sort($keys); $constructor = array_search($keys, $constructors); if ($constructor!==false) { $this->{$constructor}($args); } else { print 'not found'; } } } $d = new D(['color' => 1, 'name' => 2]);
In my opinion, these are the most correct decisions.
Создать класс с несколькими конструкторами- define the behavior directly in the__constructmethod, the magic__calldoes not work for it. - vp_arth__construct(...$params)? It will be possible to transfer any number of parameters to the constructor - ilyaplot