Re: Object Undefinded index

From: Date: Thu, 30 Oct 2003 09:40:43 +0000
Subject: Re: Object Undefinded index
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-168132@lists.php.net to get a copy of this message
I'm just adding a working example to my last post; check the implementation part at the end of the script; Cheers, Allex -------------------- <?php class Item {
    var $_productID;
    var $_quantity;
    function Item($productID, $quantity) {
      $this->_productID = $productID;
      $this->_quantity = $quantity;
    }
    function setProductID($productID) {
      $this->_productID = $productID;
    }
    function getProductID() {
      return $this->_productID;
    }
    function setQuantity($quantity) {
      $this->_productID = $quantity;
    }
    function getQuantity() {
      return $this->_quantity;
    }
} class Cart {
    var $_items;
    function Cart() {
      $this->_items = array();
    }
    function addItem($item) {
      $this->_items[] = $item;
    }
    function getItems() {
      return $this->_items;
    }
} // test implementation $MyCart = new Cart(); $MyCart->addItem(new Item("10", 20)); $MyCart->addItem(new Item("20", 45)); $MyCart->addItem(new Item("30", 55)); foreach ($MyCart->getItems() as $item) { echo "ProductId: " . $item->getProductID() . " Quantity: " . $item->getQuantity() . "<br>"; } ?> Steve Turner wrote:
I am just learning to use objects. I am messing around with a shopping cart object, but am having confusing problems. I am getting an undefined index error when trying to assign a key value pair to an array variable within an object. I am confused becuase I believe this is how you assign array variables outside an object. It acts like the variable is undefined. Thanks for the help. Steve Turner //-------------------------------------------------- class Cart {
    var $items;  // Items in shopping cart
    // Add $quantity articles of $product_id to the cart
    function add_item ($product_id, $quantity = 1)
    {
        $this->items[$product_id] += $quantity;
    }
    // Take $quantity articles of $product_id out of the cart
    function remove_item ($product_id, $quantity)
    {
        if ($this->items[$product_id] > $quantity)
{
            $this->items[$product_id] -= $quantity;
            return true;
        }
else {
            return false;
        }
    }
} //I am interacting with the object with the following code $cart = new Cart; $cart->add_item("10", 1); foreach ($cart as $product_id => $quantity) { echo $product_id . "<br>" . $quantity; }


« previous php.general (#168132) next »