doujiao3998 2008-11-24 21:14
浏览 58
已采纳

PHP对象作为虚拟数组

I have an object that implements ArrayAccess, Iterator and Countable. That produces a nigh-perfect array masking. I can access it with offsets ($object[foo]), I can throw it into a foreach-loop, and many other things.

But what I can't do is give it to the native array iterator functions (next(), reset(), current(), key()), even though I have implemented the required methods from Iterator. PHP seems to stubbornly try to iterate through its member variables, and entirely disregards the iterator-methods.

Is there an interface that would hook the object to the remaining array-traversing-functions, or am I stuck with what I have?

Update: IteratorAggregate doesn't seem to be the answer either. While it is used in foreach-loops, the basic array iterator functions don't call the methods.

  • 写回答

3条回答 默认 最新

  • dongqiyou0303 2008-11-24 21:55
    关注

    Recent changes in PHP prevent ArrayIterators form being manipulated using the standard array functions (reset, next, etc).

    This should be restored soon: http://news.php.net/php.internals/42015

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • douxueke5653 2008-11-24 21:25
    关注

    Is ArrayIterator not what you're looking for? Or what about ArrayObject, which seems to be SPL's interface for what you're trying to achieve.

    评论
  • drhwb470572 2008-11-24 21:36
    关注

    One way to get this to work is to define your own iterator in a separate class, and then tell your main class to use that new iterator instead of the default one.

    class MyIterator implements Iterator {
      public function key() {
        //
      }
    
      public function rewind() {
        //
      }
    
      // etc.
    
    }
    
    class MyMainClass implements IteratorAggregate {
      private $_data = array();
    
      // getIterator is required for the IteratorAggregate interface.
      public function getIterator() {
        return new MyIterator($this->_data);
      }
    
      // etc.
    
    }
    

    Then you should have as much control as you need. (And you can reuse your own MyIterator across a number of classes).

    No testing done on the above, but the principle is correct, I believe.

    Hope this helps!

    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥40 找同学帮敲Python代码
  • ¥15 MYSQL 订单的商品明细重复计算问题
  • ¥15 微信实时共享位置修改
  • ¥100 TG的session协议号转成直登号号后客户端登录几分钟后自动退出设备
  • ¥50 共模反馈回路的小信号增益
  • ¥15 arduino ssd1306函数与tone函数放歌代码不兼容问题
  • ¥70 0.96版本hbase的row_key里含有双引号,无法deleteall
  • ¥15 诊断性META分析合并效能的检验
  • ¥15 请问abb根据色块判断奇偶数并根据批次号放入仓储
  • ¥66 开发PC客户端一定也要开发上位机吗?