Ryan
Ryan

Reputation: 6055

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
    }
}

Upvotes: 1

Views: 165

Answers (2)

Thielicious
Thielicious

Reputation: 4442

I know this question is old and this is a duplicate topic actually but still probably interesting for people who stumble in here.

Since PHP 5.6+ you can use the ellipsis ... called the Splat operator.

function func(...$manyArgs) {
    foreach ($manyArgs as $each) {
        // do something with $each argument 
    }
}

RFC

Or since PHP 7.1 there exists a type hint called iterable

function func(iterable $args) {
    foreach ($args as $arg) {
        // awesome stuff
    }
}

RFC

Soon it'll be less of a mess once PHP 8 is out because you no longer have to declare properties before assignments anymore.

Using your code, this constructor boilerplate:

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

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

will soon be shortened to:

class Rump {
    public function __construct(
        private $var1, 
        private $var2, 
        private $var3) {}
}

RFC

Hence it will even be more useful in combination with iterable. Splat operators are not allowed. Note that this will be only working for constructors.

class Rump {
    public function __construct(private iterable $vars) {}
}

Upvotes: 0

deceze
deceze

Reputation: 522101

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.

Upvotes: 4

Related Questions