Re: Object Undefinded index
| From: | Allex | Date: | Thu, 30 Oct 2003 09:02:27 +0000 |
| Subject: | Re: Object Undefinded index | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-168126@lists.php.net to get a copy of this message | ||
In my view, to keep the object oriented approach cleaner you should use another class for describing your item, like:
class Item {
var $_product_id;
var $_quantity;
function Item($productId, $quantity) {
$this->_product_id = $productId;
$this->_quantity = $quantity;
}
function getProductID() {
return $this->_product_id;} function getQuantity() {
return $this->_quantity;} } Then your Cart class should be defined as follows: class Cart { var $_items; function Cart() {
$this->_items = array();} function addItem($item) {
$this->_items[] = $item;} function getItem($id) {
return $this->_items[$id];} } To add a new item to the cart first create the new item by calling the items constructor and then call addItem method of the Cart class(object): $MyCart = new Cart(); ... $newItem = new Item("10", 1); $MyCart->addItem($newItem); To iterate items in a Cart you may do something like that: foreach ($MyCart->getItems as $Item) { echo($Item->getProductId(), $Item->getQuantity); } Allex 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 cartfunction add_item ($product_id, $quantity = 1) { $this->items[$product_id] += $quantity; }// Take $quantity articles of $product_id out of the cartfunction 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; }