Hey everyone,
I'm trying to create a script that will add an object to an array, which will then be stored in a session. I'd like to then access the object's properties from that stored array.
Here's the relevant part of my object class:
class Cart {
var $total = 0;
var $itemcount = 0;
var $items = array();
var $itemqtys = array();
public function add_item($item_id, $qty=1) {
if(isset($this->itemqtys[$item_id]) && $this->itemqtys[$item_id] > 0) {
// item in cart already
$this->itemqtys[$item_id] = $qty + $this->itemqtys[$item_id];
$this->update_total();
} else {
${$item_id} = Item::find_by_id($item_id);
$this->items[]= ${$item_id};
$this->itemqtys[$item_id] = $qty;
}
$this->update_total();
}
function update_total() {
$this->itemcount = 0;
$this->total = 0;
if(count($this->items > 0)) {
foreach($this->items as $item) {
$this->total = $this->total + ($this->itemprices[$item] * $this->itemqtys[$item]);
$this->itemcount++;
}
}
}
...
So I've got an array defined, and the add_item function should create an instance of the Item object using find_by_id and then store it in the items array. (find_by_id works - it finds the item in the database, instantiates it, and assigns it's properties)
The class file gets included, then the cart is instantiated and the add_item function called:
$cart =& $_SESSION['cart'];
if(!is_object($cart)) {
$cart = new Cart();
}
if(isset($_GET['insert_id'])) {
$id = $_GET['insert_id'];
$cart->add_item($id);
}
...
Then I try to echo stored objects' title:
foreach($cart->items as $item) {
echo $item->title;
}
...
There is some html surrounding that of course. But what I get back is "Notice: trying to get property of non-object..." Any idea what needs to change?
Thanks!