這是相當低效的,因爲你基本上是在每個循環上設置關聯數組的關鍵。如果需要存儲它們,我會將它們保留在本地,然後在循環完成時將它們分配給它們。另外,在調用它們時將值傳遞給方法。
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
}
}
這是否甚至工作? – alex
Ew。就這些。 –
什麼是$ my_array? –