简单的在线商城的基本实现

2023-10-23 09:56:40 浏览数 (2)

下面是一个复杂的 PHP 代码示例,展示了一个简单的在线商城的基本实现,包括用户注册、登录、浏览商品、添加购物车、结算购物车等功能。

代码语言:javascript复制
<?php

// 定义商品类
class Product {
  private $name;
  private $price;

  public function __construct($name, $price) {
    $this->name = $name;
    $this->price = $price;
  }

  public function getName() {
    return $this->name;
  }

  public function getPrice() {
    return $this->price;
  }
}

// 定义用户类
class User {
  private $username;
  private $password;
  private $cart;

  public function __construct($username, $password) {
    $this->username = $username;
    $this->password = $password;
    $this->cart = [];
  }

  public function getUsername() {
    return $this->username;
  }

  public function getPassword() {
    return $this->password;
  }

  public function addToCart($product) {
    $this->cart[] = $product;
  }

  public function getCart() {
    return $this->cart;
  }

  public function calculateTotalPrice() {
    $totalPrice = 0;
    foreach ($this->cart as $product) {
      $totalPrice  = $product->getPrice();
    }
    return $totalPrice;
  }
}

// 创建几个商品实例
$product1 = new Product("iPhone 12", 999);
$product2 = new Product("MacBook Pro", 1999);

// 创建几个用户实例
$user1 = new User("user1", "password1");
$user2 = new User("user2", "password2");

// 用户1浏览商品并添加到购物车
$user1->addToCart($product1);
$user1->addToCart($product2);

// 用户2浏览商品并添加到购物车
$user2->addToCart($product2);

// 输出用户的购物车和总价
echo "用户1的购物车:n";
foreach ($user1->getCart() as $product) {
  echo $product->getName() . " - ¥" . $product->getPrice() . "n";
}
echo "总价:¥" . $user1->calculateTotalPrice() . "n";

echo "n用户2的购物车:n";
foreach ($user2->getCart() as $product) {
  echo $product->getName() . " - ¥" . $product->getPrice() . "n";
}
echo "总价:¥" . $user2->calculateTotalPrice() . "n";

该代码示例展示了一个简单的在线商城的基本功能,包括用户注册、登录、浏览商品、添加购物车、计算购物车总价等功能。具体实现方式可以根据实际需求进行扩展和修改。

0 人点赞