PHP类调用基类扩展类函数

PHP类调用基类扩展类函数,php,class,function,oop,Php,Class,Function,Oop,我有一个基本类: class Base { public $extA; public $extB; function __construct() { } public function Init() { $this->extA = new ExtA(); $this->extB = new ExtB( $this ); } public function Test()

我有一个基本类:

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 class Test()函数, ExtA和ExtB都在扩展基类。 我的问题是:这可以吗,或者有更好、更快的解决方案

延伸也是必要的吗? 或者仅仅是这样

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

这是一种奇怪的OOP方式。 底层阶级不应该知道任何关于他们孩子的事情,所以我们应该走更正确的道路。让我们实现Decorator模式:

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!

您可以按自己的意愿继续玩下去

这里有一些非常奇怪的依赖项。你是想继承遗产吗?理论上,这在某种程度上是有效的。。。这取决于你想要的行为,如果它运行良好。类B的扩展是必要的,类A的扩展不是。@Frits van Campen抱歉,我不明白,我应该如何进行继承?@user2668398使用
扩展
实现
。看看PHP的OOP教程,实现一个没有问题的机制是毫无意义的。展示您真正的问题,我们可以为您指出一个解决方案[让它要么是继承,要么是接口…]。然而,您的方法至少很奇怪。使用装饰器然后扩展它有什么意义?只是扩展基类,你不应该在没有任何具体理由的情况下添加复杂层。也许你是对的。乍一看,我也考虑过这一点,但主题启动者可能想要的不仅仅是调用parent::test()