2011-09-29 34 views
1

有人可以告訴我,這種做foreach的方法是否有缺點?php foreach鍵作爲類變量

class someclass { 
    function foo() { 
    foreach ($my_array as $this->key => $this->value) { 
     $this->bar(); 
     $this->baz(); 
    } 
    } 
    function bar(){ 
    //do something with $this->key or $this->value 
    } 
    function baz(){ 
    //do something with $this->key or $this->value 
    } 
} 
+2

這是否甚至工作? – alex

+6

Ew。就這些。 –

+0

什麼是$ my_array? –

回答

2

這是相當低效的,因爲你基本上是在每個循環上設置關聯數組的關鍵。如果需要存儲它們,我會將它們保留在本地,然後在循環完成時將它們分配給它們。另外,在調用它們時將值傳遞給方法。

class someclass{ 
    function foo($my_array){ 
     foreach ($my_array as $key => $value){ 
      $this->loopArray[$key] = $value; 
      $this->bar(); 
      $this->baz(); 
     } 

    } 
    function bar(){ 
     //do something with $this->key or $this->value 

    } 
    function baz(){ 
     //do something with $this->key or $this->value 
    } 

} 

$obj = new someclass(); 
$my_array = array('value1','value2'); 
$obj->foo($my_array); 
var_dump($obj->loopArray); 

輸出:

class SomeClass { 
    function foo($myArray) { 
     foreach ($myArray as $key => $value){ 
      $this->bar($key); 
      $this->baz($value); 
     } 
     $this->key = $key; 
     $this->value = $value; 
    } 
    function bar($key){ 
    //do something with $this->key or $this->value 
    } 
    function baz($value){ 
    //do something with $this->key or $this->value 
    } 
} 
+0

謝謝馬特。我一直按照你的建議去做。幾分鐘前想到這個,很好奇。 – pistolshrimp

+0

'這是非常低效的,因爲你基本上是在每個循環上設置關聯數組的關鍵。「咦?你是什​​麼意思? '$ this-> key'被設置爲每次迭代的標量值(即數組項的鍵)。還是我誤解你在說什麼? –

+0

我指的是將屬性名稱解析爲內存地址所用的時間。這是因爲類的實現類似於哈希表或關聯數組。 –

0

如果您需要的鍵和值可訪問公開在你的方法,我想一起去

陣列(2){[0 ] => string(6)「value1」[1] => string(6)「value2」}