简体   繁体   中英

Property must only accept an associative array - PHP OOP

Hi so this is what i need to do:

First i have a 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 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.

Verify if it is an assoc array. (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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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