0

Is there a way for an object to be aware of the object by which it was intstantiated?

For some reason (it really goes too far to explain why), I would like to achieve something like:

class outer{
    public $x ;

    function __CONSTRUCT(){
        $this->x = "hello world";
        $innerObject = $new inner();
    }

    function echo_x(){
        echo $this->x;
    }
}

class inner() {

    function echo_var_from_outer(){
        parent::echo_x();
        // the above won't work 
    }

}

$bar = new outer();
$bar->innerObject->echo_var_from_outer();

Of course I could pass the a reference for the outer class to the inner class, but it would really help me if that weren't necessary. I do know a lot of workarounds for this problem but that is not what I'm looking for. Please tell me if an injected object has any implicit awareness of the object that instantiated it.

vincentDV
  • 181
  • 1
  • 3

1 Answers1

0

In your inner class do the following

class inner extends outer {

    function echo_var_from_outer(){
        parent::echo_x();
        // the above won't work 
    }

}
Ding
  • 3,065
  • 1
  • 16
  • 27
  • Extending the outer class will change the game rules, and it might not be possible if the inner class already extends another class. That's what object composition is for. – Sven May 01 '13 at 16:15