Home > Net >  Property must only accept an associative array - PHP OOP
Property must only accept an associative array - PHP OOP

Time:09-11

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.

CodePudding user response:

Verify if it is an assoc array. (PHP8 )

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

CodePudding user response:

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.

  • Related