Re: [PHP] Object Undefinded index
From: Allex (k24d88_at_zonnet.nl)
Date: 10/30/03
- Next message: Dave G: "Japanese entry into MySQL and into emails"
- Previous message: - Edwin -: "Re: [PHP] Echo issue RESOLVED!"
- In reply to: Steve Turner: "Object Undefinded index"
- Next in thread: Allex: "Re: [PHP] Object Undefinded index"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Thu, 30 Oct 2003 10:02:27 +0100 To: php-general@lists.php.net
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 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;
> }
>
- Next message: Dave G: "Japanese entry into MySQL and into emails"
- Previous message: - Edwin -: "Re: [PHP] Echo issue RESOLVED!"
- In reply to: Steve Turner: "Object Undefinded index"
- Next in thread: Allex: "Re: [PHP] Object Undefinded index"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]