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; }
-- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php

