簡體   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