Simulate multiple inheritance by combining.
Multiple inheritance is not supported in PHP, what if we implement code reuse for methods that use multiple classes?
That's the combination. In a class, go to set another class as a property.
In the following example, multiple inheritance is simulated.
Interface instance
Write an example of a conceptual nature. We design an online sales system, the user part is designed as follows: Divide the user into, Normaluser, Vipuser, inneruser three kinds. Requires the user to calculate the price of the product according to different discounts. and requires space for future expansion and maintenance.
The code is as follows:
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 ("design mode");
$user = new Normaluser ("Tom");
$price = Productsettle::finalprice ($user, $book, $number);
$str = "Hello, dear." $user->getname (). "
";
$str. = "Your level is". $user->getgrade (). "
";
$str. = "Your discount is". $user->getdiscount (). "
";
$str. = "Your Price is". $price;
Echo $str;
?>
http://www.bkjia.com/PHPjc/760151.html www.bkjia.com true http://www.bkjia.com/PHPjc/760151.html techarticle simulate multiple inheritance by combining. Multiple inheritance is not supported in PHP, what if we implement code reuse for methods that use multiple classes? That's the combination. Go in a class ...