This article mainly introduces about the PHP source code 24: Iterator implementation of the value is false when the reason for the iteration can not be completed, has a certain reference values, now share to everyone, the need for friends can refer to
A brief talk on PHP source code 24: The reason analysis of the inability to complete the iteration when the value is false in iterator implementation
There is a simple implementation of an iterator in the previous article and the implementation of an iterator in the YII framework, there is a problem here, when the value of the iteration contains false, when the use of the Foreach loop is ended in this place, why?
Follow the bird's way. Find the relevant clues in line 8131 of the Zend/zend_vm_execute.h file, as shown in the following code:
/* * * * if (!iter | | (Iter->index > 0 && iter->funcs->valid (iter tsrmls_cc) = = FAILURE)) {/* reached end of iteration */if (EG (Exception)) {Array->refcount--;zval_ptr_dtor (&array); Zend_vm_next_opcode ();} ZEND_VM_JMP (EX (Op_array)->opcodes+opline->op2.u.opline_num);}
For the implementation of a simple iterator, the Iter->funcs->valid (ITER tsrmls_cc) method calls the valid () method,
If our value is False, the value returned by current is false, and when accessed through foreach, the traversal is interrupted, and the program continues to execute the following code instead of the loop.
Solution Solutions
Separate the key and value in the array
Operation key in valid (), rewind (), next () method instead of value
Return value only in current
such as the simple implementation of the article iterator and the implementation of the Cmapiterator in the Yii framework based on the implementation of the iterator in the YII framework
The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!