Page 322 - Beginning PHP 5.3
P. 322
Part III: Using PHP in Practice
Try It Out Create a Simple Shopping Cart
In this example, you use sessions to build a very simple shopping cart for an online store. There are
three products to choose from, and users can add any or all of the products to their cart, remove
products from the cart, and view the contents of the cart.
Save the following code as shopping_cart.php and run the script in your Web browser. Click the
Add Item links to add the items to your cart then click the Remove links to remove them again. Figure
10 - 3 shows the shopping cart in action.
< ?php
session_start();
class Product {
private $productId;
private $productName;
private $price;
public function __construct( $productId, $productName, $price ) {
$this- > productId = $productId;
$this- > productName = $productName;
$this- > price = $price;
}
public function getId() {
return $this- > productId;
}
public function getName() {
return $this- > productName;
}
public function getPrice() {
return $this- > price;
}
}
$products = array(
1 = > new Product( 1, “SuperWidget”, 19.99 ),
2 = > new Product( 2, “MegaWidget”, 29.99 ),
3 = > new Product( 3, “WonderWidget”, 39.99 )
);
if ( !isset( $_SESSION[“cart”] ) ) $_SESSION[“cart”] = array();
if ( isset( $_GET[“action”] ) and $_GET[“action”] == “addItem” ) {
addItem();
} elseif ( isset( $_GET[“action”] ) and $_GET[“action”] == “removeItem” ) {
removeItem();
} else {
displayCart();
}
284
9/21/09 9:05:13 AM
c10.indd 284 9/21/09 9:05:13 AM
c10.indd 284