Definition:
1. Generator: "An array of dynamically generated content", which is produced only when the value is used.
2. Use with: keyword yield foreach
Recommended: "php training"
Process:
1. As a generator method, it is equivalent to defining an array;
2. Each occurrence of yield in the generator is equivalent to defining a value that appears in the array;
3.foreach will traverse all yield-defined values (a defined value (expression)) in the generator. Only when it is used, other expressions between the current yield and the previous yield will be executed. , the expression after the current yield will not be executed);
4. If foreach ends normally (not break), determine whether there are other expressions after the last yield in the generator that have not been executed. If so, , execute it;
5. Different from threads, it is not executed in parallel. It just switches execution back and forth between the main business logic and the generator, which only saves space but not time.
Imagine the usage scenario:
1. Get the big data file and read it line by line in the generator;
2,? ? ?
Example:
gen.php
<?php function gen() { echo '生成器开始执行' . PHP_EOL; for ($i = 0; $i < 5; $i++) { echo '产生数据之前:' . $i . PHP_EOL; yield $i; echo '产生数据之后:' . $i . PHP_EOL; } echo '再来一个数据' . PHP_EOL; yield 5; echo '生成器执行结束' . PHP_EOL; } $gen_func = gen(); echo '生成器开始执行了吗?' . PHP_EOL; foreach ($gen_func as $key => $val) { echo '使用数据前' . PHP_EOL; echo '使用数据:' . $val . PHP_EOL; echo '使用数据后' . PHP_EOL; //if ($key >= 4) { //break; //} }
Execution result:
php gen.php 生成器开始执行了吗? 生成器开始执行 产生数据之前:0 使用数据前 使用数据:0 使用数据后 产生数据之后:0 产生数据之前:1 使用数据前 使用数据:1 使用数据后 产生数据之后:1 产生数据之前:2 使用数据前 使用数据:2 使用数据后 产生数据之后:2 产生数据之前:3 使用数据前 使用数据:3 使用数据后 产生数据之后:3 产生数据之前:4 使用数据前 使用数据:4 使用数据后 产生数据之后:4 再来一个数据 使用数据前 使用数据:5 使用数据后 生成器执行结束
part Interpretation of the execution process:
1. Line 14 does not call the generator gen(), but only defines it;
2. After entering the foreach loop, start calling gen();
3. When $val needs a value, remember the current position a and execute the generator;
4. Execute to the place defined by yield and get the value. Remember the current position b. , return to position a;
5. Loop steps 3 and 4;
6. End of loop, execute the remaining part after the last defined place of yield;
7. Remove the comments on lines 20, 21, and 22 and execute, "Use data: 4 After using data", there will be no other output.
Others (only PHP7.1.14 version verified)
1, value);//YES value;//NO
2, OK After using yield val;
3 and PHP7, yield from can call generators, arrays, use return, etc.
For more programming related content, please pay attention to the Programming Tutorial column on the php Chinese website!
The above is the detailed content of PHP generator - dynamically generate array of content. For more information, please follow other related articles on the PHP Chinese website!