1.2.76. Avoid option arrays in constructors

Avoid option arrays in constructors. Use one parameter per injected element.

<?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.76.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.76.2. Specs

Short name

Classes/AvoidOptionArrays

Rulesets

All, Analyze, Class Review

Exakat since

1.7.9

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

Medium

Features

constructor

Available in

Entreprise Edition, Exakat Cloud