开发者

php - extending classes issue

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 t开发者_StackOverflow社区he $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 :)


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;
    }
}


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜