PHP5.5迭代生成器用法实例详解,php5.5生成器
PHP5.5迭代生成器用法实例详解,php5.5生成器
本文实例讲述了PHP5.5迭代生成器用法。分享给大家供大家参考,具体如下:
PHP5.5引入了迭代生成器的概念,迭代的概念早就在PHP有了,但是迭代生成器是PHP的一个新特性,这跟python3中的迭代生成器类似,看看PHP5.5的迭代生成器如何定义。
<?php function xrange($start, $end, $step = 1) { for ($i = $start; $i <= $end; $i += $step) { yield $i; } } foreach (xrange(1, 1000000) as $num) { echo $num, "\n"; }
注意关键字:yield,正是这个yeild关键字构建了一个迭代器,这个函数xrange跟以往的函数的不同之处就在这里。一般情况都是return一个值,而yield一个值就表示这是个迭代器,每循环一次这个迭代器就生成这个值,故名为迭代生成器,迭代生成器这个函数可以进行foreach循环,每次都产生一个值。
PHP5.5之前是通过定义类实现Iterator接口的方式来构造迭代器,通过yield构造迭代器将更加提升性能节省系统开销。
这种方法的优点是显而易见的.它可以让你在处理大数据集合的时候不用一次性的加载到内存中,甚至你可以处理无限大的数据流。
如上面例子所示,这个迭代器的功能是生成从1到1000000的数字,循环输出,那么使用以往的方式是生成好这1到1000000的数字到数组中,将会十分占用内存,因为是事先就要生成好所有结果,而不是用的时候按需生成,也就是说调用xrange这个迭代器的时候,里面的函数还没有真正的运行,直到你每一次的迭代。
再看看PHP官网的例子:
<?php function xrange($start, $limit, $step = 1) { for ($i = $start; $i <= $limit; $i += $step) { yield $i; } } echo 'Single digit odd numbers: '; /* * Note that an array is never created or returned, * which saves memory. */ foreach (xrange(1, 9, 2) as $number) { echo "$number "; } echo "\n"; ?>
这里的xrange是一个迭代,功能和range是一样的,如果使用range函数的话,那么函数内部实现会储存每个迭代的中间过程,即每个中间变量都有 个内存空间,那么首先程序使用的内存空间就大了,而且分配内存,回收内存都会导致程序的运行时间加长。但是如果使用上yield实现的xrange函数的 话,里面所有的中间变量都只使用一个内存$i,这样节省的时间和空间都会变小。
那么为什么yield会有这样的效果呢?联想到lua中的yield,这里就算是协程的概念了。在lua语言中,当程序运行到yield的时候,使用协程 将上下文环境记录住,然后将程序操作权归还到主函数,当主函数调用resume的时候,会重新唤起协程,读取yield记录的上下文。这样形成了程序语言 级别的多协程操作。php 5.5这里的yield也是同样的道理,当程序运行到yield的时候,当前程序就唤起协程记录上下文,然后主函数继续操作,只是php中没有使用如 resume一样的关键字,而是“在使用的时候唤起”协程。比如上例中的foreach迭代器就能唤起yield。所以上面的这个例子就能理解了。
更多关于PHP相关内容感兴趣的读者可查看本站专题:《php操作office文档技巧总结(包括word,excel,access,ppt)》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。
您可能感兴趣的文章:
- 如何把php5.3版本升级到php5.4或者php5.5
- PHP5.5和之前的版本empty函数的不同之处
- PHP5.5在windows安装使用memcached服务端的方法
- php5.5中类级别的常量使用介绍
- php5.5新数组函数array_column使用
- php可应用于面包屑导航的迭代寻找家谱树实现方法
- php使用递归与迭代实现快速排序示例
- PHP迭代器的内部执行过程详解
- PHP迭代器实现斐波纳契数列的函数
- PHP设计模式之迭代器模式的深入解析

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Since this year, Zhou Hongyi, the founder of 360 Group, has been inseparable from one topic in all his public speeches, and that is artificial intelligence large models. He once called himself "the evangelist of GPT" and was full of praise for the breakthroughs achieved by ChatGPT, and he was firmly optimistic about the resulting AI technology iterations. As a star entrepreneur who is good at expressing himself, Zhou Hongyi's speeches are often full of witty remarks, so his "sermons" have also created many hot topics and indeed added fuel to the fire of large AI models. But for Zhou Hongyi, being an opinion leader is not enough. The outside world is more concerned about how 360, the company he runs, responds to this new wave of AI. In fact, within 360, Zhou Hongyi has already initiated a change for all employees. In April, he issued an internal letter requesting every employee and every employee of 360

Loops and Iterations: Core Concepts in Programming Loops and iterations are essential concepts in programming that allow a program to repeatedly execute a set of instructions. Loops are used to explicitly specify the number of repetitions, while iterations are used to iterate over the elements in a collection or data structure. Types of Loops There are three main types of loops: 1. for loop A for loop is used to execute a block of code when you know the number of repetitions. Its syntax is as follows: for (initialization; condition; increment/decrement) {//code block to be executed repeatedly} For example, the following for loop prints the numbers 1 to 10: for(inti=1;i

TreeMap is a class of JavaCollectionFramework that implements the NavigableMap interface. It stores the map's elements in a tree structure and provides an efficient way to store key-value pairs in sorted order. In other words, it always returns elements in ascending order. However, Java provides several methods for traversing a TreeMap in descending order. In this article, we will explore the method of traversing a TreeMap in reverse order. Iterate over a TreeMap in reverse order in Java We will print the elements of a TreeMap in reverse order using the following method: Using TreeMap.descendingMap() method Using TreeMap.de

To learn the implementation method of jQuery iteration from scratch, you need specific code examples. jQuery is a popular JavaScript library that is widely used in web development. Among them, iteration is one of the commonly used operations in jQuery. Through iteration, a set of elements can be traversed and corresponding operations performed. This article will introduce how to learn the implementation of jQuery iteration from scratch, focusing on the basic principles of iteration and specific code examples. 1. Basic principles of iteration In jQuery, the implementation of iteration mainly relies on

How to use the fileinput module for file iteration in Python3.x In Python programming, we often need to operate files, such as reading file contents, writing file contents, etc. When processing multiple files, the fileinput module can be used to easily perform file iteration operations. This article will introduce how to use the fileinput module for file iteration in Python3.x and provide code examples. The fileinput module is the Python standard library

Loops and Iterations: Concept Analysis A loop is a control structure that allows a block of code to be executed repeatedly a specified number of times or until a specific condition is met. Python provides a variety of loop types, including for loops, while loops and do-while loops. On the other hand, iteration is an abstract concept that represents the process of traversing the elements of a sequence in order. Python provides tools such as iterators and generators to implement iteration. Loop vs. Iteration: Similarities and Differences Execution Mechanism: Loops explicitly control the execution flow, while iterations are performed implicitly through iterator objects. State management: Loops maintain their own state (such as counters or conditions), while iterators encapsulate state management. Usage scenarios: Loops are suitable for times that need to be repeated a fixed number of times or until the

How to use loop statements to implement iterative calculations in Java. In programming, we often need to perform some repetitive calculations or operations. At this time, loop statements play an important role. In Java, there are three forms of loop statements: for loop, while loop and do-while loop. These loop statements can help us implement iterative calculations, that is, through multiple loops to gradually approach the desired result. The following will introduce in detail how to use these loop statements to implement iterative calculations in Java, and give corresponding code examples.

Loops A loop is a structure that repeatedly executes a block of code until a specific condition is met. Python provides a variety of loop types: for loop: used to traverse each element in a sequence (such as a list, tuple). foritemin[1,2,3,4,5]:print(item)#Output: 1,2,3,4,5while loop: used to execute the code block repeatedly as long as the condition is true. count=0whilecount
