0

I have a outer class that has another class as a member ( following the principle composition over inheritance ). Now I need to call a method of the outer class from the class within.

class Outer
{
    var $inner;
    __construct(Inner $inner) {
        $this->inner = $inner;
    }
    function outerMethod();
}
class Inner
{
    function innerMethod(){
// here I need to call outerMethod()
    }
}

I see as a solution to add a reference in Outer::__construct :

$this->inner->outer = $this;

This allows me to call the outer method like this in Inner::innerMethod :

$this->outer->outerMethod();

Is this a good solution or is there a better alternative ?

Lorenz Meyer
  • 19,166
  • 22
  • 75
  • 121
  • Is there a specific reason for inner class calling the outer? Why not something like calling outer method with inner as parameter, so as not to create circular dependancies? – Bolek Tekielski Dec 02 '14 at 12:39
  • The reason is : the inner class is a specialisation of the outer. There are several possible classes that implement an InnerInterface. The outer class contains the invariable methods and the inner class contains the specialisation specific methods. – Lorenz Meyer Dec 02 '14 at 12:50

1 Answers1

1

Best idea would be to include the outer class as a member variable of the inner.

E.g.

class Inner
{
    private $outer;
    function __construct(Outer $outer) {
        $this->outer= $outer;
    }
    function innerMethod(){
// here I need to call outerMethod()
       $this->outer->outerMethod();
    }
}

If it's not possible to construct the inner with the outer initially, you can put a setOuter method on the inner and call it when you pass it into the Outer.

E.g.

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();
    }
}

NOTE: var as a specification as a membed variable type is deprecated. Use public, protected or private instead. Advice - err on the side of private unless you have reasons not to.

Rob Baillie
  • 3,436
  • 2
  • 20
  • 34