Page 2 of 2

Re: Polymorphic Extendable Base Class

Posted: Sat Jul 11, 2009 7:51 pm
by josh
astions wrote:That's how you call methods in a parent class from a class that has the same method name. It's not really static. AFAIK. Am I missing something?
Yes.

Code: Select all

 
// wrong way to build a framework     
class Foo
{
    function calculatePrice()
    {
        return 5;
    }
}
 
class Bar extends Foo
{
    function calculatePrice()
    {
        if( rand(1,2) == 1 )
        {
            return 5 * 2;
        }
        return parent::calculatePrice();
    }
}
 
// correct
class Foo
{
    protected $price = 5;
    
    function calculatePrice()
    {
        return $this->doCalcPrice( $this->price );
    }
    
    protected function doCalcPrice( $price )
    {
        return $price;
    }
}
 
class Bar extends Foo
{
    protected $price = 10;
}
 
// or
 
class Bar extends Foo
{
    protected function doCalcPrice( $price )
    {
        return $price * 2;
    }
}
 
Notice in the last 2 examples the subclass Bar is less coupled in less ways to the abstract Foo class. I consider calling super to be static, not sure if it technically is but it has similar implications to the flexibility of your program