以下是一个使用PHP类的继承和多态实现购物的例子:
// 定义商品类
class Product {
protected $name;
protected $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 Book extends Product {
protected $author;
public function __construct($name, $price, $author) {
parent::__construct($name, $price);
$this->author = $author;
}
public function getAuthor() {
return $this->author;
}
}
class Clothing extends Product {
protected $size;
public function __construct($name, $price, $size) {
parent::__construct($name, $price);
$this->size = $size;
}
public function getSize() {
return $this->size;
}
}
// 定义购物车类
class ShoppingCart {
protected $items = [];
public function addItem(Product $product) {
$this->items[] = $product;
}
public function getTotalPrice() {
$totalPrice = 0;
foreach ($this->items as $item) {
$totalPrice += $item->getPrice();
}
return $totalPrice;
}
}
// 创建商品实例
$book = new Book("PHP入门教程", 50, "John Doe");
$clothing = new Clothing("T恤衫", 20, "XL");
// 创建购物车实例
$cart = new ShoppingCart();
// 添加商品到购物车
$cart->addItem($book);
$cart->addItem($clothing);
// 输出购物车总价
echo "购物车总价:" . $cart->getTotalPrice();
在上面的例子中,我们定义了一个Product
类作为基类,然后定义了Book
和Clothing
类作为其子类。Book
和Clothing
类继承了Product
类的属性和方法,并添加了自己特有的属性和方法。
然后我们定义了一个ShoppingCart
类,用于管理购物车中的商品。addItem
方法接受一个Product
对象作为参数,将其添加到购物车中。getTotalPrice
方法遍历购物车中的商品,计算总价并返回。
最后,我们创建了一个Book
和Clothing
实例,并将它们添加到购物车中。最后输出购物车的总价。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站