繁体   English   中英

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

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

嗨,这是我需要做的:

首先我有一个 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;
    }

然后我有另一个 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;
    }

我需要做的是属性产品必须只接受一个关联数组,其中数组的键是产品的名称,数组的值将是 class 产品的对象。

验证它是否是一个 assoc 数组。 (PHP8+)

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

我可能会做这样的事情(未经测试):

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

如果需要,您还可以将该 foreach 循环移动到产品的设置器中。

暂无
暂无

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

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