我创建了一个对象,它被命名为洗车场。我创建了一个会话并为会话分配了该对象,如果我输入数量然后按购买按钮,我有结果(示例 6):
您的购物车包含 6 件商品。
但是当我什么都不输入时,我得到:
您的购物车包含物品。
我应该怎么做?谢谢!这是我的所有代码:
index.php
PHP 代码:
<?php
session_start();
require_once 'carwash.php';
if (isset($_SESSION['encoded_cartopass'])) {
// first let's get the variable from the session
$encoded_cartopass = $_SESSION['encoded_cartopass'];
// now let's unpack it
$cartopass = unserialize($encoded_cartopass);
// echo quantity
echo "Your shopping cart contains {$cartopass->getQuantity()} items. <br /><br />";
}
else {
echo "Your shopping cart contains 0 items. <br /><br />";
}
?>
<form action="process.php" method="post">
Quantity: <input type="text" name="quantity" id="quantity"/>
<input type="submit" value="Buy" name="submit" />
</form>
process.php
PHP 代码:
<?php
require_once 'carwash.php';
if (isset($_POST['submit'])) {
if (!isset($_SESSION['encoded_cartopass'])) {
// construct and set quantity
$cartopass = new carwash();
$cartopass->setQuantity($_POST['quantity']);
// construct and encode session
session_register('encoded_cartopass');
$_SESSION['encoded_cartopass'] = serialize($cartopass);
}
else {
// if session is existing, decode it and
// increment quantity
$encoded_cartopass = $_SESSION['encoded_cartopass'];
$cartopass = unserialize($encoded_cartopass);
$cartopass->incrementQuantity($_POST['quantity']);
// encode class and assign to session and
// session is used pass to index.php
$_SESSION['encode_cartopass'] = serialize($cartopass);
}
}
echo "<script>window.location.href='index.php'</script>";
?>
carwash.php
PHP 代码:
<?php
class carwash {
private $carmake;
private $caryear;
private $quantity;
public function getCarmake() {
return $this->carmake;
}
public function setCarmake($carmake) {
$this->carmake = $carmake;
}
public function getCaryear() {
return $this->caryear;
}
public function setCaryear($caryear) {
$this->caryear = $caryear;
}
public function getQuantity() {
return $this->quantity;
}
public function setQuantity($quantity) {
$this->quantity = $quantity;
}
public function incrementQuantity($quantity = '') {
if (empty($quantity)) {
$this->quantity++;
}
else {
$this->quantity += $quantity;
}
}
public function washcar() {
echo "scruba, dub, dub, scruba, dub, dub <br />";
echo "I'm feelling cleaner, Thank you!";
}
}
?>