1.2.79. Avoid option arrays in constructors¶
Avoid option arrays in constructors. Use one parameter per injected element.
Arrays carry only the options at hand. They skip default values, or do not carry any checks and are prone to typos.
<?php
class Foo {
// Distinct arguments, all typehinted if possible
function __construct(A $a, B $b, C $c, D $d) {
$this->a = $a;
$this->b = $b;
$this->c = $c;
$this->d = $d;
}
}
class Bar {
// One argument, spread over several properties
function __construct(array $options) {
$this->a = $options['a'];
$this->b = $options['b'];
$this->c = $options['c'];
$this->d = $options['d'];
}
}
?>
See also Avoid option arrays in constructors and PHP RFC: Named Arguments (Type-safe and documented options).
1.2.79.1. Connex PHP features¶
1.2.79.1.1. Suggestions¶
Spread the options in the argument list, one argument each.
Use a configuration class, that hold all the elements with clear names, instead of an array.
Use named parameters to pass and document the arguments.
1.2.79.1.2. Specs¶
Short name |
Classes/AvoidOptionArrays |
Rulesets |
|
Exakat since |
1.7.9 |
PHP Version |
All |
Severity |
Minor |
Time To Fix |
Quick (30 mins) |
Precision |
Medium |
Available in |