Overriding grandparents methods in php

I am currently writing a set of skeleton classes for an application, starting with the StoreLogic base class, which has tax rules, discount rules, etc. Classes Cart, Order, Quote, etc. will extend StoreLogic as they will all use the same set of methods that StoreLogic supports.

As soon as these main classes are completed, I will implement them by expanding Cart, Order, Quote AND StoreLogic, since each application of these classes will differ depending on the needs of different clients. Redefining methods from parent classes is easy, but redefining grandparents' classes before their children expanded them seems ... impossible? I have a feeling that I am doing it wrong (tm) .. and I think that someone more experienced as you might be able to point me in the right direction. Take a look at the code and see what you think!

/* 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.. 
+4
source share
1 answer

I think the basic logic is missing here.

 - MyCart extends Cart - Cart extends StoreLogic 

If you want to use MyStoreLogic then cart should be defined as

  abstract class Cart extends MyStoreLogic 

If you do not want to do this, you can have

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

Class modification

 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; } } 
+3
source

All Articles