Php 类组合-从内部类调用外部方法
我有一个外部类,它有另一个类作为成员(遵循组合优先于继承的原则)。现在我需要从内部的类调用外部类的方法Php 类组合-从内部类调用外部方法,php,oop,composition,Php,Oop,Composition,我有一个外部类,它有另一个类作为成员(遵循组合优先于继承的原则)。现在我需要从内部的类调用外部类的方法 class Outer { var $inner; __construct(Inner $inner) { $this->inner = $inner; } function outerMethod(); } class Inner { function innerMethod(){ // here I need to call o
class Outer
{
var $inner;
__construct(Inner $inner) {
$this->inner = $inner;
}
function outerMethod();
}
class Inner
{
function innerMethod(){
// here I need to call outerMethod()
}
}
我认为在Outer::u构造中添加引用是一种解决方案:
$this->inner->outer = $this;
这允许我在Inner::innerMethod中调用如下外部方法:
$this->outer->outerMethod();
这是一个好的解决方案还是有更好的替代方案?最好的办法是将外部类作为内部类的成员变量 例如 如果最初无法用外部构造内部,可以在内部放置
setOuter
方法,并在将其传递到outer
时调用它
例如
注意:
var
作为membed变量类型的规范已被弃用。使用public
、protected
或private
。建议-除非您有理由不这样做,否则会在private方面出错。内部类调用外部类是否有特定的原因?为什么不调用外部方法,将内部作为参数,这样就不会创建循环依赖关系呢?原因是:内部类是外部类的特殊化。有几个可能的类实现InnerInterface。外部类包含不变的方法,内部类包含特定于专业化的方法。
class Inner
{
private $outer;
function __construct(Outer $outer) {
$this->outer= $outer;
}
function innerMethod(){
// here I need to call outerMethod()
$this->outer->outerMethod();
}
}
class Outer
{
private $inner;
function __construct(Inner $inner) {
$inner->setOuter( $this );
$this->inner = $inner;
}
function outerMethod();
}
class Inner
{
private $outer;
function setOuter(Outer $outer) {
$this->outer= $outer;
}
function innerMethod(){
// here I need to call outerMethod()
$this->outer->outerMethod();
}
}