2012-03-12 67 views
1

我有2个继承自father类的类。 “父级”类有一个protected变量,这个变量正在填充在child这两个类中,每个类都为它填充不同的数据库信息。类继承和实例交互

我的问题是,当我创建两个类的实例时,第二个实例更改第一个实例的值。

下面是代码:

class User 
{ 
    //array with the MySQL Server details// 
    private $serverInfoArray = array("host" => HOST, "user" => USER, "pass" => PASS); 

    protected $data; //This will be populated with data in both of the "child" classes. 

    //some database connection functions....// 

    public function setData(){} //implemented on "child" classess 

    public function getData(){} //implemented on "child" classess 

} 

,这里是一个child类:

class Producer extends User 
{ 

    function __construct($id) 
    { 
     $this->setData($id); 
    } 

    public function setData($id) 
    { 
     global $serverInfoArray, $data; 
     $connectionFB; 

     $query = "MY FIRST QUERY"; //IN THE SECOND CHILD CLASS 
            //IT HAS DIFFERENT QUERY 

     $result = mysql_query($query, $connectionFB); 

     $i=0; 

     while($row = mysql_fetch_array($result)) 
     { 
      $data[$i] = $row; 
      $i++; 
     }  
    } 

    public function getData() 
    { 
     global $data; 
     return $data;  
    } 
} 

第二类具有相同的结构,但其名称不同,正在执行的查询。其声明是class Account extends User

当我创建2个实例:

$producer = new Producer($_SESSION['PRODUCER_ID']); 
$account = new Account($_SESSION['ACCOUNT_ID']); 

,并做到这一点:

var_dump($producer->getData()); 

我得到的是由第二查询填充的$data值。如果我不创建account实例,它将返回第一类中填充的值。

为什么account实例从producer类实例更改$data的值,我如何区分它们?

谢谢。

+1

你开始关于受保护的类变量的问题,但实际的方法不使用它们。没有帮助;) - 为什么你不在父/基类中做实际的mysql查询? – hakre 2012-03-12 14:27:26

回答

3
  1. 删除以下行:

    global $serverInfoArray, $data; 
    
  2. 使用$this->serverInfoArray & $this->data访问类变量。

+0

谢谢,我确定知道使用'$ this',但是因为我在访问类变量时遇到了输入错误('$ this - > $ data'而不是'$ this-> data'),我遇到了问题并开始放弃全局定义......现在一切都很好,我再次安排了我的思想,谢谢:) – 2012-03-12 15:51:32

0

$ data不是全局变量,那么为什么使用global

您应该使用$this->data$this->serverInfoArray

+0

我试过使用它,但它没有填充结果数组 – 2012-03-12 14:25:34

+0

你也应该使用$ this-> serverInfoArray – soju 2012-03-12 14:26:05

+0

@Alon_A你应该使用$ this,当你引用类变量时 – 2012-03-12 14:30:08