php实现商品类
商品类的基本结构
在PHP中实现商品类,通常需要定义商品的基本属性(如名称、价格、库存等)和方法(如获取信息、更新库存等)。以下是一个基础的实现示例:

class Product {
private $id;
private $name;
private $price;
private $stock;
public function __construct($id, $name, $price, $stock) {
$this->id = $id;
$this->name = $name;
$this->price = $price;
$this->stock = $stock;
}
public function getId() {
return $this->id;
}
public function getName() {
return $this->name;
}
public function getPrice() {
return $this->price;
}
public function getStock() {
return $this->stock;
}
public function updateStock($quantity) {
$this->stock += $quantity;
}
}
扩展商品类的功能
可以添加更多属性和方法以满足实际需求,例如商品分类、折扣计算、描述信息等:

class Product {
private $id;
private $name;
private $price;
private $stock;
private $category;
private $description;
private $discount = 0;
public function __construct($id, $name, $price, $stock, $category, $description) {
$this->id = $id;
$this->name = $name;
$this->price = $price;
$this->stock = $stock;
$this->category = $category;
$this->description = $description;
}
public function setDiscount($discount) {
$this->discount = $discount;
}
public function getFinalPrice() {
return $this->price * (1 - $this->discount / 100);
}
public function getDetails() {
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->price,
'final_price' => $this->getFinalPrice(),
'stock' => $this->stock,
'category' => $this->category,
'description' => $this->description
];
}
}
数据库交互
商品类通常需要与数据库交互,以下是一个简单的数据库操作示例:
class ProductRepository {
private $db;
public function __construct($db) {
$this->db = $db;
}
public function save(Product $product) {
$stmt = $this->db->prepare("INSERT INTO products (name, price, stock) VALUES (?, ?, ?)");
$stmt->execute([$product->getName(), $product->getPrice(), $product->getStock()]);
}
public function findById($id) {
$stmt = $this->db->prepare("SELECT * FROM products WHERE id = ?");
$stmt->execute([$id]);
$data = $stmt->fetch();
return new Product($data['id'], $data['name'], $data['price'], $data['stock']);
}
}
实际应用示例
创建一个商品对象并调用其方法:
$product = new Product(1, "Laptop", 999.99, 10, "Electronics", "High-performance laptop");
$product->setDiscount(10);
echo $product->getFinalPrice(); // 输出折扣后的价格
print_r($product->getDetails()); // 输出商品详细信息
通过以上方式,可以灵活扩展商品类的功能,满足不同的业务需求。






