Take the 2-minute tour ×

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

$master = new MasterClass();


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

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 :)

share|improve this question
i am not sure what exactly is the problem, but is it not possible to pass the object of the MasterClass to EventProcess->doSomething? –  Sabeen Malik Mar 19 '10 at 17:33
Yes you're quite right, i've since realised the domain i was testing on was set to run as php4 by cpanel whereas i beleive php5 passes it by reference by default. –  Iain Mar 19 '10 at 17:52

1 Answer 1

up vote 3 down vote accepted

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;
share|improve this answer
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 Mar 19 '10 at 17:50
+1. That's by far the easiest way to go about it. An alternative would be to use a Visitor Pattern: sourcemaking.com/design_patterns/visitor –  Gordon Mar 19 '10 at 17:50
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 Mar 20 '10 at 7:04
@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 웃 Mar 20 '10 at 11:04
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 Mar 20 '10 at 14:43

Your Answer


