Is there a way, in PHP5.3, for an object $enclosed to know which object $enclosing that it is inside of? Essentially I want to make some variables of $enclosing be accessible only to $enclosed without specifically passing those vars in.

class Enclosing {
  private $enclosed;//Enclosed object
  private $othervar;

  function __construct($a,$b){
     $this->enclosed= new Enclosed($b);


class Enclosed {
  private $myvar;

  function __construct($a){

  function where_am_i() {//get reference to Enclosing object


I am working on a Calendar that can display multiple Schedules which have multiple, possibly recurring Events. I am using PHPs DateTime, DateInterval and DatePeriod objects for date handling (they make dealing with timezones and recurrence easier despite their other drawbacks). Currently my design goes like this:

A Calendar object has a DatePeriod called $window which contains all the display dates. e.g. the month of May, 1957.

The Calendar also has an array $schedules of Schedule objects. Each member of $schedules must be aware of $window. So I implemented the Observer pattern between Calendar and Schedule.

Similarly each Schedule has an array $events of Events, which because they may be recurring, must also be aware of $window. So I implemented the Observer pattern between Schedule and Event.

All of this means that I have a cascade of copying the $window to multiple other objects every time it changes.

It would be much more efficient if the Events in $events knew who their enclosing Schedule was and that Schedule knew who its enclosing Calendar was. Then when these objects needed to use $window they could just ask for it.

Any thoughts on a good way of making this happen? Is there a pattern I can refer to?


This is theoretically impossible. The object is not "enclosed" in anything at all; in an instance of the Enclosing class, you merely enclose a reference to that object. There could be many references all over the place to the same Enclosed instance.

You might be able to declare Enclosed inside the Enclosing class, but I'm not sure if PHP supports inner classes.

Otherwise, just pass a reference to the Enclosing object when creating the Enclosed object, and store that in a field of the Enclosed object.

I had a feeling I was looking for magic. But I thought perhaps my $enclosed could examine (via Reflection?) all the instances of $enclosing and find the one that contained itself.

There isn't a way to directly access an object that 'encloses' another object. You either need to pass a reference to the enclosed object, or keep the data in a variable in the enclosed object.