php - 扩展类问题

时间:2011-02-23 16:48:40

标签: php

我有一个包含几个单独类的主类,我想将它们连接在一起,这样我就可以共享在主类中定义的变量。问题是只有第一个slave类可以读取$ x变量,每个后续的slave类(我有20个其他)将$ x显示为空白。例如:

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

我在这里做错了吗?我以前从未使用过扩展类,所以我不知道我在做什么:)

2 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分:1)

为了完整起见,这里是使用可见性修饰符(私有,受保护,公开)的Gaurav答案的副本。

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