Domanda

Given the following class hierarchy of in general unknown depth:

class P
{
    protected static $var = 'foo';

    public function dostuff()
    {
        print self::$var;
    }

}

class Child extends P
{
    protected static $var = 'bar';

    public function dostuff()
    {
        parent::dostuff();
        print self::$var;
    }
}

class GrandChild extends Child
{
    protected static $var = 'baz';

    public function dostuff()
    {
        parent::dostuff();
        print self::$var;
    }
}

$c = new GrandChild;
$c->dostuff(); //prints "foobarbaz"

Can I somehow get rid of the redefinitions of dostuff() while maintaining functionality?

È stato utile?

Soluzione

This should do it

class P
{
    protected static $var = 'foo';

    public function dostuff()
    {
        $hierarchy = $this->getHierarchy();
        foreach($hierarchy as $class)
        {
            echo $class::$var;
        }
    }

    public function getHierarchy()
    {
        $hierarchy = array();
        $class = get_called_class();
        do {
            $hierarchy[] = $class;
        } while (($class = get_parent_class($class)) !== false);
        return array_reverse($hierarchy);
    }

}

class Child extends P
{
    protected static $var = 'bar';
}

class GrandChild extends Child
{
    protected static $var = 'baz';  
}

$c = new GrandChild;
$c->dostuff();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top