2012-12-19 41 views
4

我目前正在爲一個應用程序編寫一組骨架類,從一個名爲StoreLogic的基類開始,它包含稅法,折扣規則等。類Cart,Order,Quote等將擴展因爲它們都使用StoreLogic提供的同一套方法。在php中覆蓋祖父法中的方法

一旦這些核心類完成,我將通過擴展Cart,Order,Quote和StoreLogic來實現它們,因爲這些類的每個應用程序將根據我們的各種客戶端需求而不同。從父類中覆蓋方法很容易,但是在他們的孩子擴展他們之前凌駕祖父母類似乎是不可能的?我感覺我做錯了這個方式(tm)..我認爲像你這樣更有經驗的人也許能夠指引我走向正確的方向。看看代碼,看看你的想法!

/* My core classes are something like this: */ 
abstract class StoreLogic 
{ 
    public function applyDiscount($total) 
    { 
     return $total - 10; 
    } 
} 

abstract class Cart extends StoreLogic 
{ 
    public function addItem($item_name) 
    { 
     echo 'added' . $item_name; 
    } 
} 

abstract class Order extends StoreLogic 
{ 
    // .... 
} 

/* Later on when I want to use those core classes I need to be able to override 
* methods from the grandparent class so the grandchild can use the new overriden 
* methods: 
*/ 
class MyStoreLogic extends StoreLogic 
{ 
    public function applyDiscount($total) { 
     return $total - 5; 
    } 
} 

class MyOrder extends Order 
{ 
    // ... 
} 

class MyCart extends Cart 
{ 
    public $total = 20; 

    public function doDiscounts() 
    { 
     $this->total = $this->applyDiscount($this->total); 
     echo $this->total; 
    } 
} 

$cart = new MyCart(); 
$cart->doDiscounts(); // Uses StoreLogic, not MyStoreLogic.. 

回答

3

我想你是在這裏失去了一個非常基本的邏輯

- MyCart extends Cart 
- Cart extends StoreLogic 

如果你想使用MyStoreLogic然後cart應該被定義爲

abstract class Cart extends MyStoreLogic 

如果你不想那麼你可以有

$cart = new MyCart(); 
$cart->doDiscounts(new MyStoreLogic()); // output 15 

類修改

class MyCart extends Cart { 
    public $total = 20; 
    public function doDiscounts($logic = null) { 
     $this->total = $logic ? $logic->applyDiscount($this->total) : $this->applyDiscount($this->total); 
     echo $this->total; 
    } 
} 
+0

正確的,我不希望因爲這將是一個庫的一部分改車。考慮一下,理想情況下,我希望MyCart擴展MyStoreLogic和Cart ...我不認爲PHP能做到這一點?!當然,將邏輯對象傳遞給父方法可能是唯一的方法 –

+0

第二種方法在這裏被稱爲組合嗎?看起來很明智......但是讓我想知道什麼時候應該使用組合,何時使用繼承? –