douying1119 2009-07-15 19:15
浏览 55
已采纳

PHP相当于Python的yield运算符

In Python (and others), you can incrementally process large volumes of data by using the 'yield' operator in a function. What would be the similar way to do so in PHP?

For example, lets say in Python, if I wanted to read a potentially very large file, I could work on each line one at a time like so (this example is contrived, as it is basically the same thing as 'for line in file_obj'):

def file_lines(fname):
    f = open(fname)
    for line in f:
        yield line
    f.close()

for line in file_lines('somefile'):
    #process the line

What I'm doing right now (in PHP) is I'm using a private instance variable to keep track of state, and acting accordingly each time the function is called, but it seems like there must be a better way.

  • 写回答

6条回答 默认 最新

  • dongshi2458 2009-07-15 19:25
    关注

    PHP has a direct equivalent called generators.

    Old (pre php 5.5 answer):

    Unfortunately, there isn't a language equivalent. The easiest way is to either to what you're already doing, or to create a object that uses instance variables to maintain state.

    There is however a good option if you want to use the function in conjunction with the foreach-statement: SPL Iterators. They can be used to achieve something quite similar to python generators.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 ADS生成的微带线为什么是蓝色空心的
  • ¥15 求一下解题思路,完全不懂
  • ¥15 tensorflow
  • ¥15 densenet网络结构中,特征以cat方式复用后是怎么进行误差回传的
  • ¥15 STM32G471芯片spi设置了8位,总是发送16位
  • ¥15 R语言并行计算beta-NTI中tree文件的类型
  • ¥15 如何解读marsbar导出的ROI数据?
  • ¥20 求友友协助弄一下基于STC89C52单片机的声光控制灯原理图
  • ¥15 arduino双向交通灯设计
  • ¥15 有没有会粒子群算法的大能(○゜ε^○)求带不会出收敛图😭