Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将值传递给类构造函数(变量与数组)_Php_Oop_Design Patterns_Solid Principles - Fatal编程技术网

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

Php 将值传递给类构造函数(变量与数组),php,oop,design-patterns,solid-principles,Php,Oop,Design Patterns,Solid Principles,我有一个名为Items的类,在实例化时该类应该接收5+个值。 我知道向构造函数传递超过(3-4)个变量表明设计很差 将这个数量的变量传递给构造函数的最佳实践是什么 我的第一个选择: class Items { protected $name; protected $description; protected $price; protected $photo; protected $type; public function __constru

我有一个名为Items的类,在实例化时该类应该接收5+个值。 我知道向构造函数传递超过(3-4)个变量表明设计很差

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

我的第一个选择:

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;
    }
第二种选择:

class Items {
    protected $attributes;

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

    public function name()
    {
        return $this->attributes['name'];
    }
}
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;
}

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

class Items {
    protected $attributes;

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

    public function name()
    {
        return $this->attributes['name'];
    }
}
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;
}

你应该使用混合溶液。将数组传递给构造函数。在构造函数
中,提取该数组并单独分配变量。在
Items
中提取引用除方法
name
之外的所有ok。谢谢,我相信这是我能得到的最好的方法,我可以调用$Items->getAttributes()->name,时间复杂度为O(1),而不是每次使用循环。干杯:)