views:

27

answers:

1

I'm not certain how to explain this with the correct terms so maybe an example is the best method...

$master = new MasterClass();

$master->doStuff();

class MasterClass {

    var $a;
    var $b;
    var $c;
    var $eventProccer;

    function MasterClass() 
    {
        $this->a = 1;
        $this->eventProccer = new EventProcess();
    }

    function printCurrent()
    {
        echo '<br>'.$this->a.'<br>';
    }

    function doStuff()
    {
        $this->printCurrent();
        $this->eventProccer->DoSomething();
        $this->printCurrent();
    }
}


class EventProcess {

    function EventProcess() {}

    function DoSomething() 
    {
        // trying to access and change the parent class' a,b,c properties

    }
}

My problem is i'm not certain how to access the properties of the MasterClass from within the EventProcess->DoSomething() method? I would need to access, perform operations on and update the properties. The a,b,c properties will be quite large arrays and the DoSomething() method would be called many times during the execuction of the script. Any help or pointers would be much appreciated :)

+2  A: 

This has been discussed a number of times on SO, every time with the result that there is no "native" way of doing this. You would have to pass a reference to the MasterClass instance to the child class. In PHP5:

 $this->eventProccer = new EventProcess($this);

and store it in the child class like so:

 class EventProcess
  {
    private $masterClass; // Reference to master class

    function __construct($masterClass) 
      {
        $this->masterClass = $masterClass;
      }
Pekka
Thats great thankyou, i was worried about overhead in terms of resources used but i presume if its passed by reference any overhead would be minimal.
Iain
+1. That's by far the easiest way to go about it. An alternative would be to use a Visitor Pattern: http://sourcemaking.com/design_patterns/visitor
Gordon
This code is suitable for PHP4 or PHP4 compatibility in PHP5. `var` is deprecated in PHP5. This will trigger E_STRICT warning in PHP5.3 and up. Use `protected`, `public` or `private`.
takeshin
@takeshin good point, changed var to private. It will however not work as desired in PHP 4, as the object will not be passed as a reference.
Pekka
@Pekka It's up to Iain to decide which one to use. We do not know, why he used `var` in his sample. Maybe he is still on PHP4. Then, `var` is OK.
takeshin