简体   繁体   English

属性只能接受关联数组 - PHP OOP

[英]Property must only accept an associative array - PHP OOP

Hi so this is what i need to do:嗨,这是我需要做的:

First i have a class:首先我有一个 class:



class Product
{
    private $name;
    private $price;
    private $sellingByKg;


    public function __construct($name = null, $price = null, $sellingByKg = null)
    {
        $this->name = $name;
        $this->price = $price;
        $this->sellingByKg = $sellingByKg;
    }

    public function getName()
    {
        return $this->name;
    }
    public function getPrice()
    {
        return $this->price;
    }
    public function getSellingByKg()
    {
        return $this->sellingByKg;
    }

Then i have another class that extends the Products class:然后我有另一个 class 扩展产品 class:


class MarketStall extends Product
{
    public $products;

    public function __construct(
        $products= [],
        $name = null,
        $price = null,
        $sellingByKg = null
    ) {
        parent::__construct($name, $price, $products);
        $this->products = $products;
    }

What i need to do is the property products must only accept an associative array where the keys of the array are the names of the products and the values of the array will be objects of the class Product.我需要做的是属性产品必须只接受一个关联数组,其中数组的键是产品的名称,数组的值将是 class 产品的对象。

Verify if it is an assoc array.验证它是否是一个 assoc 数组。 (PHP8+) (PHP8+)

if (array_is_list($products)) {
    throw new Exception("Assoc array expected");
}

I would probably do something like this (not tested):我可能会做这样的事情(未经测试):

class MarketStall extends Product
{
    public $products;

    public function __construct(
        $products= [],
        $name = null,
        $price = null,
        $sellingByKg = null
    ) {
        parent::__construct($name, $price, $sellingByKg); // You probably meant $sellingByKg here?

        foreach ($products as $key => $product) {
            // If not a Product or the key isn't equal to the product name
            if (!($product instanceof Product::class) || ($key !== $product->getName())) {
                throw new \Exception('Not a valid products array!');
            }
        }

        $this->products = $products;
    }

You can also move that foreach loop into a setter for the products, should you need one.如果需要,您还可以将该 foreach 循环移动到产品的设置器中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM