下面是一个简单的 PHP 实现的玉石交易系统:
<?php
// 定义一个玉石类,包含名称、价格、数量等属性
class Gemstone {
public $name;
public $price;
public $quantity;
public function __construct($name, $price, $quantity) {
$this->name = $name;
$this->price = $price;
$this->quantity = $quantity;
}
}
// 定义一个交易类,用于实现购买和出售玉石的操作
class Transaction {
public $gemstones;
public function __construct() {
$this->gemstones = array();
}
// 购买玉石
public function buyGemstone($gemstone) {
array_push($this->gemstones, $gemstone);
}
// 出售玉石
public function sellGemstone($gemstone) {
$index = array_search($gemstone, $this->gemstones);
if ($index !== false) {
unset($this->gemstones[$index]);
}
}
}
// 创建一些玉石实例
$diamond = new Gemstone("钻石", 1000, 5);
$ruby = new Gemstone("红宝石", 500, 10);
$emerald = new Gemstone("翡翠", 800, 15);
// 创建一个交易实例
$transaction = new Transaction();
// 购买一些玉石
$transaction->buyGemstone($diamond);
$transaction->buyGemstone($ruby);
// 查询已购买的玉石
print_r($transaction->gemstones);
// 出售一些玉石
$transaction->sellGemstone($diamond);
// 查询剩余的玉石
print_r($transaction->gemstones);
?>
以上代码中,定义了一个 Gemstone 类表示玉石,包含名称、价格、数量等属性。同时定义了一个 Transaction 类用于实现购买和出售玉石。
继续完善代码续写:
<?php
// 继续完善玉石类,添加一个输出玉石信息的方法
class Gemstone {
public $name;
public $price;
public $quantity;
public function __construct($name, $price, $quantity) {
$this->name = $name;
$this->price = $price;
$this->quantity = $quantity;
}
public function printInfo() {
echo "玉石名称:{$this->name},价格:{$this->price},数量:{$this->quantity}<br>";
}
}
// 继续完善交易类,添加一个计算总价值的方法
class Transaction {
public $gemstones;
public function __construct() {
$this->gemstones = array();
}
public function buyGemstone($gemstone) {
array_push($this->gemstones, $gemstone);
}
public function sellGemstone($gemstone) {
$index = array_search($gemstone, $this->gemstones);
if ($index !== false) {
unset($this->gemstones[$index]);
}
}
public function totalValue() {
$total = 0;
foreach ($this->gemstones as $gemstone) {
$total += $gemstone->price * $gemstone->quantity;
}
return $total;
}
}
// 创建一些玉石实例
$diamond = new Gemstone("钻石", 1000, 5);
$ruby = new Gemstone("红宝石", 500, 10);
$emerald = new Gemstone("翡翠", 800, 15);
// 创建一个交易实例
$transaction = new Transaction();
// 购买一些玉石
$transaction->buyGemstone($diamond);
$transaction->buyGemstone($ruby);
$transaction->buyGemstone($emerald);
// 查询已购买的玉石
echo "已购买的玉石:<br>";
foreach ($transaction->gemstones as $gemstone) {
$gemstone->printInfo();
}
// 计算总价值
$totalValue = $transaction->totalValue();
echo "总价值:{$totalValue}