0

I have a master class with several separate classes that I want to link up together so I can share variables defined in the master class. The problem is only the first slave class can read the $x variable, every subsequent slave class (I have 20 others) shows $x as blank. For example:

class Master {
    var $x;
    function initialize{) {
        $this->x = 'y';
    }   
}

class Slave1 extends Master {
    function process(){
        echo $this->x;
    }
}
class Slave2 extends Master {
    function process(){
        echo $this->x;
    }
}

Am I doing something wrong here? I've never used extended classes before so I've no idea what I'm doing :)

5
  • 1
    Can you show the calling code? Are you running ->initialize() on every single instance? Commented Feb 23, 2011 at 16:50
  • 1
    its good practice to use access modifier instead of using var Commented Feb 23, 2011 at 16:51
  • 2
    If you want process to echo 'y' you'll need to add __construct to the Master class. Or call initialize on manually Commented Feb 23, 2011 at 16:54
  • @SeRPRo You should not edit the question that way, you should post your solution as an answer. Commented Feb 23, 2011 at 16:56
  • @Albin sorry I thought he needs to approve the changes. Sorry :) Commented Feb 23, 2011 at 16:59

2 Answers 2

3
class Master {
    var  $x;  // should use protected or public
    function __construct() {
        $this->initialize();
    }

    function initialize{) {
       $this->x = 'y';
    }   
}

class Slave1 extends Master {
    function process(){
        echo $this->x;
    }
}
class Slave2 extends Master {
    function process(){
        echo $this->x;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

For completeness, here is a copy of Gaurav's answer using visibility modifiers (private, protected, public).

class Master {
    protected $x;
    public function __constructor() {
        $this->x = 'y';
    }
}

class Slave1 extends Master {
    public function process() {
        // do stuff
        echo $this->x;
    }
}

class Slave2 extends Master {
    public function process() {
        // do other stuff
        echo $this->x;
    }
}

// Usage example
$foo = new Slave1();
$bar = new Slave2();
$foo->process();
$bar->process();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.