lundi 22 mai 2017

Passing values to class constructor (variables vs array)

I have a class named Items, on instantiation the class should receive 5+ values. I know that passing more than (3-4) variables to the constructor indicates a poor design.

What is the best practice for passing this number of variables to constructor?

My first option:

class Items {

    protected $name;
    protected $description;
    protected $price;
    protected $photo;
    protected $type;

    public function __construct($name, $description, $price, $photo, $type)
    {
        $this->name = $name;
        $this->description = $description;
        $this->price = $price;
        $this->photo = $photo;
        $this->type = $type;
    }

    public function name()
    {
        return $this->name;
    }

and the second option:

class Items {
    protected $attributes;

    public function __construct(array $attributes)
    {
        $this->attributes = $attributes;
    }

    public function name()
    {
        return $this->attributes['name'];
    }
}

Aucun commentaire:

Enregistrer un commentaire