php foreach key as a class variable
Can someone please tell me if this method of doing foreach has drawbacks?
class someclass {
function foo() {
foreach ($my开发者_Go百科_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
}
}
It's pretty inefficient as you are essentially setting the key to an associative array on each loop. I would keep them local and then assign them when the loop is done if you need to store them. Also, pass the values to the methods when you call them.
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
}
}
If you need the keys and values to be accessible publicly in your methods, I'd go with:
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);
Outputs:
array(2) { [0]=> string(6) "value1" [1]=> string(6) "value2" }
精彩评论