在PHP中覆盖父类的方法

4

我目前正在编写一组应用程序的骨架类,从一个名为StoreLogic的基类开始,该类包含税收规则、折扣规则等。类Cart、Order、Quote等将扩展StoreLogic,因为它们都使用StoreLogic提供的相同一组方法。

一旦这些核心类完成,我将通过扩展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..
1个回答

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;
    }
}

没错,我不想改变购物车,因为它将成为库的一部分。仔细考虑,也许我希望MyCart扩展MyStoreLogic和Cart...但我不认为php可以做到这一点?当然,将逻辑对象传递给父方法可能是唯一的解决方法。 - John Hunt
这里的第二种方法被称为组合吗?听起来还算合理,但我想知道何时应该使用组合,何时应该使用继承? - John Hunt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接