Learning Resources
Class definition and usage
A class is a collection of variables and functions working with these variables. Variables are defined by var and functions by function. A class is defined using the following syntax:
class Cart {
var $items; // Items in our shopping cart
// Add $num articles of $artnr to the cart
function add_item($artnr, $num) {
$this->items[$artnr] += $num;
}
// Take $num articles of $artnr out of the cart
function remove_item($artnr, $num) {
if ($this->items[$artnr] > $num) {
$this->items[$artnr] -= $num;
return true;
} elseif ($this->items[$artnr] == $num) {
unset($this->items[$artnr]);
return true;
} else {
return false;
}
}
}
?>
This defines a class named Cart that consists of an associative array of articles in the cart and two functions to add and remove items from this cart.