通过组合模拟多重继承。
在php中不支持多重继承,如果我们向使用多个类的方法而实现代码重用有什么办法么?
那就是组合。在一个类中去将另外一个类设置成属性。
下面的例子,模拟了多重继承。
接口实例
写一个概念性的例子。 我们设计一个在线销售系统,用户部分设计如下: 将用户分为,normaluser, vipuser, inneruser 三种。要求根据用户的不同折扣计算用户购买产品的价格。并要求为以后扩展和维护预留空间。
代码如下:
interface user
{
public function getname();
public function setname($_name);
public function getdiscount();
}
abstract class abstractuser implements user
{
private $name = "";
protected $discount = 0;
protected $grade = "";
function __construct($_name) {
$this->setname($_name);
}
function getname() {
return $this->name;
}
function setname($_name) {
$this->name = $_name;
}
function getdiscount() {
return $this->discount;
}
function getgrade() {
return $this->grade;
}
}
class normaluser extends abstractuser
{
protected $discount = 1.0;
protected $grade = "normal";
}
class vipuser extends abstractuser
{
protected $discount = 0.8;
protected $grade = "vipuser";
}
class inneruser extends abstractuser
{
protected $discount = 0.7;
protected $grade = "inneruser";
}
interface product
{
function getproductname();
function getproductprice();
}
interface book extends product
{
function getauthor();
}
class bookonline implements book
{
private $productname;
protected $productprice;
protected $author;
function __construct($_bookname) {
$this->productname = $_bookname;
}
function getproductname() {
return $this->productname;
}
function getproductprice() {
$this->productprice = 100;
return $this->productprice;
}
public function getauthor() {
$this->author = "chenfei";
return $this->author;
}
}
class productsettle
{
public static function finalprice(user $_user, product $_product, $number) {
$price = $_user->getdiscount() * $_product->getproductprice() * $number;
return $price;
}
}
$number = 10;
$book = new bookonline("设计模式");
$user = new normaluser("tom");
$price = productsettle::finalprice($user, $book, $number);
$str = "您好,尊敬的" . $user->getname() . "
";
$str .= "您的级别是" . $user->getgrade() . "
";
$str .= "您的折扣是" . $user->getdiscount() . "
";
$str .= "您的价格是" . $price;
echo $str;
?>
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号