2015-05-05 24 views
0

我努力學習PHP類,我被困在我認爲應該努力東西..

我想聰明的代碼,而不是有很多if語句。

首先,$ QueryResult中的數據包含以下

POSITION  COUNT 
L1   5 
L2   24 
L3   87 

這裏是類 -

class WIPData 
    { 
    public $queryResult; 
    public $L1 = 0; 
    public $L2 = 0; 
    public $L3 = 0; 


    function WIPData($results) 
    { 

     $queryResult = $results; 

     while ($values = CDB::GetAssoc($queryResult)) { 
     if ($queryResult) 
     { 
      $rPos = $values['POSITION']; 
      $this->$rPos = $values['COUNT']; 

//  if ($values['POSITION'] == "L1") 
//  { 
//   $this->L1 = $values['COUNT']; 
//  } 
//  if ($values['POSITION'] == "L2") 
//  { 
//   $this->L2= $values['COUNT']; 
//  } 
//  if ($values['POSITION'] == "L3") 
//  { 
//   $this->L3= $values['COUNT']; 
//  } 
      } 
} 


    } 

} 

正如你可以看到註釋掉if語句是相當多的代碼,也有更多的職位,這將會更大..

所以我想我會盡量聰明,做

$rPos = $values['POSITION']; 
    $this->$rPos = $values['COUNT']; 

的想法是,「位置」將始終是變量的名字之一例如,L1,L2,L3,所以真的在PHP眼中的代碼將

$this->L1 = $values['COUNT']; 

但是,對於一些原因,變量不會被填充。

我在做一些不可能的事嗎?

任何建議都會非常有幫助!

+0

你是什麼意思「由完全不工作」? – BenM

+2

http://stackoverflow.com/questions/12571197/how-do-i-dynamically-write-a-php-object-property-name – MilanG

+0

謝謝@MilanG - 你引用的問題解決了我的問題! – SK2017

回答

-1

試試這個:

class WIPData { 
    public $queryResult; 
    public $L1 = 0; 
    public $L2 = 0; 
    public $L3 = 0; 

    function WIPData($results) { 
     $this->queryResult = $results; 

     if (!empty($this->queryResult)) { 
      while ($values = CDB::GetAssoc($this->queryResult)) { 
        $this->{$rPos} = $values['POSITION']; 
        $this->{$rPos} = $values['COUNT']; 
      } 
     } 
    } 
}