php foreach key作为类变量

时间:2011-09-29 02:54:11

标签: php foreach

有人可以告诉我这种做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 个答案:

答案 0 :(得分:2)

由于您实际上是在每个循环上将键设置为关联数组,因此效率非常低。我会保留它们本地,然后在循环完成时分配它们,如果你需要存储它们。另外,在调用它们时将值传递给方法。

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
    }
 }

答案 1 :(得分:0)

如果您需要在方法中公开访问密钥和值,我会选择:

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);

输出:

  

array(2){[0] => string(6)“value1”[1] => string(6)“value2”}