我有这个基类:
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都是基类的。 我的问题是:这是好的,还是有更好,更快的解决方案?
延伸也是必要的吗? 或者就这么简单
class ExtA
{
...
}
class ExtB
{
...
}
谢谢!
答案 0 :(得分:1)
这是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!
您可以按照自己想要的方式进一步玩