0

我有这个基类:

class Base
{
    public $extA;
    public $extB;

    function __construct()
    {

    }

    public function Init()
    {
        $this->extA = new ExtA();
        $this->extB = new ExtB( $this );
    }

    public function Test()
    {
        return 'Base Test Here!';
    }
}

扩展基类的 ExtA 类

class ExtA extends Base
{
    public function Test()
    {
        return 'ExtA Test Here!';
    }
}

类 ExtB 也扩展了基类

class ExtB extends Base
{
    private $base;

    public function __construct( $base )
    {
        $this->base = $base;
    }

    public function Test()
    {
        return 'ExtB calling ExtA->Test()::' . $this->base->extA->Test();
    }
}


$base = new Base();
$base->Init();

var_dump( $base->Test() );
var_dump( $base->extA->Test() );
var_dump( $base->extB->Test() );

我尝试从 ExtB 调用 ExtA 类 Test() 函数,ExtA 和 ExtB 都在扩展 Base 类。我的问题是:这样可以吗,还是有更好、更快的解决方案?

扩展也是必要的吗?或者就像这样

class ExtA
{
     ...
}
class ExtB
{
     ...
}

谢谢!

4

1 回答 1

1

这是 OOP 的奇怪方式。Base 类不应该知道任何关于它的孩子的事情,所以我们应该走更正确的方法。让我们实现装饰器模式:

interface IExt
{
    public function test();
}

abstract class ExtDecorator implements IExt
{
    protected $instance;

    public function __construct(IExt $ext)
    {
        $this->instance = $ext;
    }
}

class ExtA extends ExtDecorator
{
    public function test()
    {
        return 'ExtA::test here and calling... ' . $this->instance->test();
    }
}


class ExtB extends ExtDecorator
{
    public function test()
    {
        return 'ExtB::test is here and calling... ' . $this->instance->test();
    }
}

class Base implements IExt
{
    public function test()
    {
        return 'Base::test here!';
    }
}

class Printer
{
    public static function doMagic(IExt $ext)
    {
        echo $ext->test()."\n";
    }
}


Printer::doMagic($base = new Base); 
// Base::test here!
Printer::doMagic($extA = new ExtA($base)); 
// ExtA::test here and calling... Base::test here!
Printer::doMagic(new ExtB($extA)); 
// ExtB::test is here and calling... ExtA::test here and calling... Base::test here!

你可以以任何你想要的方式玩得更远

于 2013-08-16T19:26:02.850 回答