首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将值传递给类构造函数(变量与数组)

将值传递给类构造函数(变量与数组)
EN

Stack Overflow用户
提问于 2017-05-18 06:56:33
回答 1查看 59关注 0票数 0

我有一个名为Item的类,在实例化时,类应该接收5+值。我知道,向构造函数传递多个(3-4)变量意味着设计不当。

将这几个变量传递给构造函数的最佳实践是什么?

我的第一个选择是:

代码语言:javascript
复制
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;
    }

第二种选择是:

代码语言:javascript
复制
class Items {
    protected $attributes;

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

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

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-18 07:14:59

您拥有良好的体系结构和第一个解决方案。但是,如果您的属性是动态的,并且您不知道它们是什么,那么可以使用第二个解决方案来实现它。在这种情况下,您可以使用修改后的第二个选项:

代码语言:javascript
复制
class Items {
    protected $attributes;

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

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

$items = new Items($attributes);

foreach ($items->getAttributes() as $attribute) {
    echo $attribute->name;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44040666

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档