Xây dụng class sản phẩm
Kịch bản tạo sản phẩm cơ bản.
Phân tích:
Sản phầm gồm các thông tin sau:
- Mã sản phẩm (ID)
- Tên sản phẩm (Name)
- Giá (Price)
- Số Lượng (Quantity)
- Danh sách sản pham (Products)
Tạo class sản phẩm như sau:
Các thuộc tính của sản phẩm là:
- ID
- Name
- Price
- Quantity
- DanhSachSanPham
Ta thực hiện hóa như sau:
class Product {
public $ID;
public $Name;
public $Price;
public $Quantity;
static public $Products;
function __construct() {
self::$Products = [];
}
}
Sản phẩm có các thuộc tính như sau:
- Danh sách sản phẩm Products()
- Thêm sản phẩm AddProduct($Product)
- Xóa sản phẩm DeleteProduct($Id)
- Sửa Sản Phẩm EditProduct($Product)
- Tìm sản phẩm ProductById($Id)
Ta hiện thực hóa như sau:
Phương thức danh sách sản phẩm
// danh sách sản phẩm
function Products() {
return self::$Products;
}
Phương thức thêm sản phẩm
function AddProduct($Product) {
self::$Products[$Product["ID"]] = $Product;
}
Phương thức tìm sản phẩm
function ProductById($id) {
$a = $this->Products();
foreach ($a as $p) {
if ($p["ID"] == $id) {
return $p;
}
}
return NULL;
}
Phương thức xóa sản phẩm
function DeleteProduct($id) {
$a = $this->ProductById($id);
if ($a) {
unset(self::$Products[$id]);
}
}
Phương thức sản phẩm
function EditProduct($Product) {
$a = $this->ProductById($Product[$id]);
if ($a) {
self::$Products[$id] = $Product;
}
}
Khởi tạo đối tượng sản phẩm
function __construct($Product = null) {
if ($Product) {
$this->ID = $Product["ID"];
$this->Name = $Product["Name"];
$this->Price = $Product["Price"];
$this->Quantity = $Product["Quantity"];
}
self::$Products = [];
}
Cách dùng như sau:
include './sanpham.php';
$p = new Product();
$_p["ID"] = 1;
$_p["Name"] = "iPhone";
$_p["Price"] = 1000;
$_p["Quantity"] = 20;$p->AddProduct($_p);
$_p["ID"] = 2;
$_p["Name"] = "sam sung";
$_p["Price"] = 1200;
$_p["Quantity"] = 10;
$p->AddProduct($_p);print_r($p->Products());
?>