5

I'm trying to figure out how a foreach statement is interpreted by PHP. That led me to use gdb while executing a dummy foreach script.

I end up in zend_compile.c, in the zend_compile_foreach() function. I see the call to the macro ZEND_FE_FETCH_R that moves the internal pointer of the array/object we loop on.

There are a few things I don't understand :

  • How the value is actually returned to the zend_compile_foreach context
  • Are we nesting calls to zend_compile_stmt (and therefore zend_compile_foreach) to make the iteration happen ? So is the code compiled N times ? N being the number of elements in the array/object
  • What is an opline ?? I see that everywhere I look and I don't know about this
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
JesusTheHun
  • 1,217
  • 1
  • 10
  • 19
  • 1
    maybe interesting? [How does 'foreach' actually work?](http://stackoverflow.com/questions/10057671/how-does-foreach-actually-work) – Ryan Vincent Feb 12 '16 at 13:22
  • I've found this question/answer, but it's about foreach userland behavior, not internal implementation & execution, but thx – JesusTheHun Feb 12 '16 at 13:24
  • 2
    You're looking at the compiler code. It doesn't loop. The generated virtual machine instructions loop. Try `phpdbg -p* test.php` to see the generated instructions. – NikiC Feb 12 '16 at 14:07
  • After deeper investigation, I've came to this understanding : 1. opline is an actual instruction that will be executed by the VM. Almost everything before is lexing & compiling into these instruction. 2. zend_compile_foreach() write opline to move the internal seeker forward, write the current value of the var to that opline, execute the loop block of code, and jump back to opnum_fetch, until the fetch emit an exit via fe_fetch_r_exit. So there is no loop, only jump (sort of goto?) to previous opcode to execute code again with a new value. Am I correct ? – JesusTheHun Feb 16 '16 at 17:21

0 Answers0