> 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.
My last post didn't actually address the error you mentioned though, so I might as well do that now... :) >From your example, the warning you received is cause by the add_item( ) method because it's attempting to add 1 to the value of $cart->items['10']. The only problem is that $cart->items['10'] hasn't been defined yet. Now PHP is smart enough to realise that if $cart->items['10'] doesn't exist, it should simply create the key and assign it a blank value (i.e. 0) and *then* add 1. So any subsequent calls to $cart->add_item("10", 1) won't generate an warning. It's also important to note that you only received a warning, not an error, and that code finished executing properly. You only received the warning because you had rerror reporting set to strict, which is normally a very good idea to help keep your code clean and bug free. The reason the code didn't work as expected was because of the bug addressed in my last post. To code the add_item( ) method in a way that won't trigger this warning, you can change it to: function add_item ($product_id, $quantity = 1) { if (!isset($this->items[$product_id])) { $this->items[$product_id] = 0; } $this->items[$product_id] += $quantity; } You can see that the code checks to see if the the key exists, and if it doesn't sets it to 0, before attempting to add to it's value. This is essentially replicating what PHP was doing anyway. Cheers, Al -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php