PHP根据用户折扣计算商品价格

步骤01

创建User.php界面,在该界面中首先申明一个User接口,用户都是对该接口实现的

<?php
interface User{
		function getName();
		function setName($name);
		function getDiscount();
}
abstract class AbstractUser implements User{
	private $name="";
	protected $discount=0;
	protected $grade="";
	public function __construct($name){
		$this->setName($name);
	}
	public function getName(){
		return $this->name;
	}
	public function getDiscount(){
		return $this->discount;
	}
	public function setName($name){
		$this->name=$name;
	}
	public function getGrade(){
		return $this->grade;
	}
}
/**
* 普通用户
*/
class NormalUser extends AbstractUser
{
	protected $discount=1.0;
	protected $grade="NormalUser";
} 
/**
* VIP用户
*/
class VIPlUser extends AbstractUser
{
	protected $discount=0.8;
	protected $grade="VIPUser";
} 
/**
* 内部用户
*/
class InnerlUser extends AbstractUser
{
	protected $discount=0.7;
	protected $grade="InnerlUser";
} 

?>

步骤02

对商品进行设计,首先申明一个Product接口;然后Book接口继承该接口;最后创建BookOnline类实现Book接口
<?php
/*
*定义产品接口
*/
Interface Product{
	public function getProductName();
	public function getProductPrice();
}
interface Book extends Product{
	public function getAuthor();
}

/**
* 
*/
class BookOnline implements Book
{
	private $productName;
	private $producePrice;
	private $author;
	function __construct($bookName)
	{
		$this->productName=$bookName;
	}
	public function getProductName(){
		return $this->productName;
	}
	public function getProductPrice(){
		$this->productPrice=100;
		return $this->productPrice;
	}
	public function getAuthor(){
		return $this->author;
	}
}
?>

步骤03

创建ProductSettle类,他是一个独立的计算类,使用静态方法进行商品计算
<?php
	include_once 'User.php';
	include_once 'Product.php';
class ProductSettle{
	public static function finalPrice(User $_user, Product $_product, $number=1){
		$price = $_user->getDiscount()*$_product->getProductPrice()*$number;
		return $price;
	}
}
?>

步骤04

创建用户测试界面Test.php页面
<?php
	include_once 'User.php';
	include_once 'Product.php';
	include_once 'ProductSettle.php';
	$number=10;
	$book = new BookOnline("PHP+MySQL");
	$user = new NormalUser("Tom");
	$price = ProductSettle::finalPrice($user,$book,$number);
	$str="您好!尊敬的用户 ".$user->getName()."</br>";
	$str.="您的级别是".$user->getGrade()."</br>";
	$str.="您的折扣是".$user->getDiscount()."</br>";
	$str.="购买$number 本《".$book->getProductName()."》总价格是 ".$price."</br>";
	echo $str;
?>
结果图
PHP根据用户折扣计算商品价格_第1张图片


你可能感兴趣的:(PHP根据用户折扣计算商品价格)