Skip to content
Advertisement

Any way to simplify PHP constructor arguments?

When I want to pass values into a PHP constructor I have to go:

class Rump {
    private $var1;
    private $var2;
    private $var3;

    public function __construct($var1, $var2, $var3) {
        $this->var1 = $var1;
        $this->var2 = $var2;
        $this->var3 = $var3;
    }
}

is there a simpler way to do it? something like

class Rump {
    public function __construct($var1, $var2, $var3) {
        //call a function here
    }
}

Advertisement

Answer

public function __construct($var1, $var2, $var3) {
    foreach (array('var1', 'var2', 'var3') as $var) {
        $this->$var = $$var;
    }
}

or:

public function __construct() {
    foreach (array('var1', 'var2', 'var3') as $i => $var) {
        $this->$var = func_get_arg($i);
    }
}

or:

public function __construct() {
    list($this->var1, $this->var2, $this->var3) = func_get_args();
}

But really, rather than saving a line or two and trying to be clever, using explicit assignment is usually preferred because it’s very easy to understand, even if boring. If you find that you have too many arguments to type out one by one, maybe you have too many arguments.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement