程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> php使用接口與組合模擬多繼承

php使用接口與組合模擬多繼承

編輯:關於PHP編程

通過組合模擬多重繼承。

在PHP中不支持多重繼承,如果我們向使用多個類的方法而實現代碼重用有什麼辦法麼?

那就是組合。在一個類中去將另外一個類設置成屬性。

下面的例子,模擬了多重繼承。

接口實例

寫一個概念性的例子。 我們設計一個在線銷售系統,用戶部分設計如下: 將用戶分為,NormalUser, VipUser, InnerUser 三種。要求根據用戶的不同折扣計算用戶購買產品的價格。並要求為以後擴展和維護預留空間。

代碼如下:
<?php
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;
?>


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved