PDA

View Full Version : Some help with php classes


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

Cj Shadows
01-05-2007, 01:59 AM
Umm as you know I don't know PHP but just trying to help.

$ncart = new Cart;
$ncart->add_item("aa", 1, 20, 10);
$ncart->add_item("bb", 7, 20, 10);
$ncart->print_cart();

I'm not sure if it is case sensative but it looks like you have Cart and cart there. Maybe change them both to lowercase or capital?

Dennis56
01-05-2007, 02:06 AM
No its different the function is with a lowercase and the class is uppercase so its right the way i have it

Cj Shadows
01-05-2007, 02:10 AM
Oh okay sorry I couldnt help you :/

Dennis56
01-05-2007, 02:12 AM
No Problem im suspecting something with the array and the foreach loop

ok nvm guys i fixed it i should have wrote it like this
class Cart {
var $items;
var $money;

function add_item($item_id, $num, $cost) {
$money = 20;
if($money > $cost){
$this->items[$cost] -= $money;
$this->items[$item_id] += $num;
unset($this->items[$cost]);
return true;
}elseif($money == $cost){
unset($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, 10);
$ncart->add_item("bb", 7, 10);
$ncart->print_cart();