Dennis56
01-05-2007, 01:26 AM
Could someone tell me whats wrong with this code?
class Cart {
var $items;
function add_item($item_id, $num, $money, $cost) {
$this->items[$num] *= $cost;
if($this->items[$money] > $cost){
$this->items[$cost] -= $money;
$this->items[$item_id] += $num;
unset($this->items[$cost]);
return true;
}elseif($this->items[$money] == $cost){
unset($this->items[$money]);
unset($this->items[$cost]);
$this->items[$item_id] += $num;
return true;
}else {
unset($this->items[$cost]);
return false;
}
}
function remove_item($item_id, $num) {
if ($this->items[$item_id] > $num) {
$this->items[$item_id] -= $num;
return true;
} elseif ($this->items[$item_id] == $num) {
unset($this->items[$item_id]);
return true;
} else {
return false;
}
}
function print_cart(){
$keys = array_keys($this->items);
foreach ($keys as $key) {
print $key. "=";
print $this->items[$key]."<br>";
}
}
}
$ncart = new Cart;
$ncart->add_item("aa", 1, 20, 10);
$ncart->add_item("bb", 7, 20, 10);
$ncart->print_cart();
The output of the code is
1=0
7=0
it should be
aa=1
bb=7
It appears to only show the cost and not the name of the item
It for learning purposes not actually going to use it anywhere
class Cart {
var $items;
function add_item($item_id, $num, $money, $cost) {
$this->items[$num] *= $cost;
if($this->items[$money] > $cost){
$this->items[$cost] -= $money;
$this->items[$item_id] += $num;
unset($this->items[$cost]);
return true;
}elseif($this->items[$money] == $cost){
unset($this->items[$money]);
unset($this->items[$cost]);
$this->items[$item_id] += $num;
return true;
}else {
unset($this->items[$cost]);
return false;
}
}
function remove_item($item_id, $num) {
if ($this->items[$item_id] > $num) {
$this->items[$item_id] -= $num;
return true;
} elseif ($this->items[$item_id] == $num) {
unset($this->items[$item_id]);
return true;
} else {
return false;
}
}
function print_cart(){
$keys = array_keys($this->items);
foreach ($keys as $key) {
print $key. "=";
print $this->items[$key]."<br>";
}
}
}
$ncart = new Cart;
$ncart->add_item("aa", 1, 20, 10);
$ncart->add_item("bb", 7, 20, 10);
$ncart->print_cart();
The output of the code is
1=0
7=0
it should be
aa=1
bb=7
It appears to only show the cost and not the name of the item
It for learning purposes not actually going to use it anywhere