Recommended: "PHP Video Tutorial"
What is Generator
Starting from PHP 5.5, PHP has added a new feature, that isGenerator
, translated into Chinese as Generator
. Generators can be simply used to implement object iteration. Let's start with a small official example.
xrange
In PHP, we all know that there is a function called range
, which is used to generate an array of arithmetic sequences, and then we can use this array to perform Iteration of foreach
. Specifically, this is what I want to do.
foreach (range(1, 100, 2) as $num) { echo $num . PHP_EOL; }
This code will output an arithmetic sequence with the first term being 1, the last term being 100, and the tolerance being 2. Its execution sequence is as follows. First, range(1, 100, 2)
will generate an array, which stores an arithmetic sequence as above, and then iterate the array in foreach
.
So, a question arises, what if I want to generate 1 million numbers? Then we will occupy hundreds of megabytes of memory. Although memory is very cheap now, we can't waste memory like this. Then at this time, our generator can come in handy. Consider the following code.
function xrange($start, $limit, $step = 1) { while ($start <p>The result of this code is exactly the same as the previous code, but its internal principle is turned upside down. </p><p>We just said that in the previous code, <code>range</code> will generate an array, and then <code>foreach</code> will iterate the array to take out a certain value. But in this code, we redefined a <code>xrange</code> function. In the function, we used the keyword <code>yield</code>. We all know that when defining a function and hoping it will return a value, use <code>return</code> to return it. So this <code>yield</code> can also return a value, but it is completely different from <code>return</code>. </p><p>Using the <code>yield</code> keyword can interrupt the function while it is running, and at the same time save the context of the entire function and return an object of type <code>Generator</code>. When executing the object's <code>next</code> method, the context at the time of interruption will be reloaded and continue running until the next <code>yield</code> appears. If no <code>yield</code> appears later, , then the entire generator is considered finished. </p><p>In this way, our function call above can be written equivalently like this. </p><pre class="brush:php;toolbar:false">$nums = xrange(1, 100, 2); while ($nums->valid()) { echo $nums->current() . "\n"; $nums->next(); }
Here, $num
is an object of Generator
. We see three methods here, valid
, current
, and next
. When our function is executed and there is no yield
interrupt later, then our function in xrange
is completed, and the valid
method will become false
. As for current
, it will return the value behind the current yield
. This means that the generator function will be interrupted. Then after calling the next
method, the function will continue to execute until the next yield
appears or the function ends.
Okay, so far, we have seen that yield
is used to "generate" a value and return it. In fact, yield
can also be written like this $ret = yield;
. Like the return value, here a value is passed into the function when continuing to execute the function. It can be used through Generator::send($value)
. For example.
function sum() { $ret = yield; echo $ret . PHP_EOL; } $sum = sum(); $sum->send('I am from outside.');
In this way, the program will print out the string passed in by the send
method. There can be calls on both sides of yield
at the same time.
function xrange($start, $limit, $step = 1) { while ($start valid()) { echo $nums->current() . "\n"; $nums->send($nums->current() + 1); }
For use like this, send()
can return the return of the next yield
.
Other Generator methods
Generator::key()
For yield
, we can use yield $id => $value
, this is, we can get $id
through the key
method, and the current
method returns $value
.
Generator::rewind()
This method can help us restart the execution of the generator and save the context. At the same time, it will return the first yield
return Content. When the send
method is executed for the first time, rewind
will be called implicitly.
Generator::throw()
This method throws an exception to the generator.
Postscript
yield
As a new feature of PHP 5.5, we use a new method to iterate data efficiently. At the same time, we can also use yield
to implement coroutines.
The above is the detailed content of Take you to understand Generator in PHP. For more information, please follow other related articles on the PHP Chinese website!

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools

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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
