购物车使用面向对象的PHP

时间:2015-12-14 16:08:32

标签: php arrays class oop object

我最近在OO购物车上发现了一些在线代码。结果显示如下,购物车中已有商品。

  

购物车内容(2项)

     

一些小工具:1 @ $ 23.45每个。

     

另一个小工具:4个,每个12.39美元。

我的目标是拥有类似下面的内容,但产品列表允许用户将项目本身添加/移除到购物车中(如上所述),但使用按钮并允许用户自行更改数量。任何人都可以帮我解决这个问题吗?我还听说过人们在购物车中使用会话?感谢任何帮助,谢谢!

  

产品清单

     

一些小工具:每个23.45美元。数量(1)添加到购物车

     

另一个小工具:每个12.39美元。数量(1)添加到购物车

     

     

另一个小工具:12.39美元。数量(4)删除

ShoppingCart.php

<?php
class ShoppingCart implements Iterator, Countable {

// Array stores the list of items in the cart:
protected $items = array();

// For tracking iterations:
protected $position = 0;

// For storing the IDs, as a convenience:
protected $ids = array();

// Constructor just sets the object up for usage:
function __construct() {
    $this->items = array();
    $this->ids = array();
}

// Returns a Boolean indicating if the cart is empty:
public function isEmpty() {
    return (empty($this->items));
}

// Adds a new item to the cart:
public function addItem(Item $item) {

    // Need the item id:
    $id = $item->getId();

    // Throw an exception if there's no id:
    if (!$id) throw new Exception('The cart requires items with unique ID
    values.');

    // Add or update:
    if (isset($this->items[$id])) {
        $this->updateItem($item, $this->items[$item]['qty'] + 1);
    } else {
        $this->items[$id] = array('item' => $item, 'qty' => 1);
        $this->ids[] = $id; // Store the id, too!
    }

    } // End of addItem() method.

    // Changes an item already in the cart:
    public function updateItem(Item $item, $qty) {

    // Need the unique item id:
    $id = $item->getId();

    // Delete or update accordingly:
    if ($qty === 0) {
        $this->deleteItem($item);
    } elseif ( ($qty > 0) && ($qty != $this->items[$id]['qty'])) {
        $this->items[$id]['qty'] = $qty;
    }

    } // End of updateItem() method.

    // Removes an item from the cart:
    public function deleteItem(Item $item) {

    // Need the unique item id:
    $id = $item->getId();

    // Remove it:
    if (isset($this->items[$id])) {
        unset($this->items[$id]);

        // Remove the stored id, too:
        $index = array_search($id, $this->ids);
        unset($this->ids[$index]);

        // Recreate that array to prevent holes:
        $this->ids = array_values($this->ids);

    }

    } // End of deleteItem() method.

    // Required by Iterator; returns the current value:
    public function current() {

    // Get the index for the current position:
    $index = $this->ids[$this->position];

    // Return the item:
    return $this->items[$index];

    } // End of current() method.

    // Required by Iterator; returns the current key:
    public function key() {
    return $this->position;
    }

    // Required by Iterator; increments the position:
    public function next() {
    $this->position++;
    }

    // Required by Iterator; returns the position to the first spot:
    public function rewind() {
    $this->position = 0;
    }

    public function valid() {
    return (isset($this->ids[$this->position]));
    }

   // Required by Countable:
   public function count() {
    return count($this->items);
   }

   } // End of ShoppingCart class.
?>

Item.php

<?php
class Item {

// Item attributes are all protected:
protected $id;
protected $name;
protected $price;

// Constructor populates the attributes:
public function __construct($id, $name, $price) {
    $this->id = $id;
    $this->name = $name;
    $this->price = $price;
}

// Method that returns the ID:
public function getId() {
    return $this->id;
}

// Method that returns the name:
public function getName() {
    return $this->name;
}

// Method that returns the price:
public function getPrice() {
    return $this->price;
}

} // End of Item class.
?>

cart.php

<?php
// Create the cart:
try {

require('includes/classes/ShoppingCart.php');
$cart = new ShoppingCart();

// Create some items:
require('includes/classes/Item.php');
$w1 = new Item('W139', 'Some Widget', 23.45);
$w2 = new Item('W384', 'Another Widget', 12.39);
$w3 = new Item('W55', 'Cheap Widget', 5.00);

// Add the items to the cart:
$cart->addItem($w1);
$cart->addItem($w2);
$cart->addItem($w3);

// Update some quantities:
$cart->updateItem($w2, 4);
$cart->updateItem($w1, 1);

// Delete an item:
$cart->deleteItem($w3);

// Show the cart contents:
echo '<h2>Cart Contents (' . count($cart) . ' items)</h2>';

if (!$cart->isEmpty()) {

foreach ($cart as $arr) {

    // Get the item object:
    $item = $arr['item'];

    // Print the item:
    printf('<p><strong>%s</strong>: %d @ $%0.2f each.<p>', $item->getName(),   
    $arr['qty'], $item->getPrice());

} // End of foreach loop!

} // End of IF.

} catch (Exception $e) {
// Handle the exception.
}
?>

更新 我尝试将以下代码添加到&#39; cart.php&#39;在创建的项目下面

<table>
<tr><td><?php echo $w1; ?></td><td><button onclick="$cart- 
 >addItem($w1);">Add to cart</button></td></tr>
 <tr><td><?php echo $w2; ?></td><td><button onclick="$cart- 
 >addItem($w2);">Add to cart</button></td></tr>
 <tr><td><?php echo $w3; ?></td><td><button onclick="$cart-    
>addItem($w3);">Add to cart</button></td></tr>
</table>

但是,我收到了这个错误......

  

捕获致命错误:第26行的cart.php中无法将类Item的对象转换为字符串

1 个答案:

答案 0 :(得分:0)

你的课程做得很好。现在您只需编辑“模板”或cart.php。

如果要打印所有项目,则必须使用“添加到购物车”按钮打印每个项目(在html中,您可以使用“添加到购物车”按钮为每个项目制作一个表单,并传递金额和项目的ID。 并在cart.php

中查看购物车中的内容
foreach ($cart as $arr) {

// Get the item object:
$item = $arr['item'];

// Print the item:
printf('<p><strong>%s</strong>: %d @ $%0.2f each.<p>', $item->getName(),   
$arr['qty'], $item->getPrice());

} // End of foreach loop!

因此,如果我理解您的问题,您只需要一种方法将项目添加到卡片中。我会这样做的。

增加: 当然你得到了那个错误。你不能打印这样的对象。我建议你在Item类(Item.php)中添加一个函数,如:

  public function printItem(){
         return $this->name." ".$this->price //Or whatever you want to print.
  }

我输入的函数名是printItem以避免保留字(只是'print'可能是危险的)

然后,在您的模板(表格)中,您可以替换

   echo $w1 by echo $w1->printItem() //Or something like that

我希望这会对你有所帮助。 =)