【无标题】

下面是一个简单的 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}

转:http://www.xiaoshuang.net/zywd/73.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值