Php is first compiled into opcode by the Zend engine. How is opcode executed by zend_execute? Is it finally compiled as a machine code? What is the specific process? Php is first compiled into opcode by the Zend engine. How is opcode executed by zend_execute? Is it finally compiled as a machine code? What is the specific process? Reply: Since Zend is mentioned by the subject, this is the PHP implemented by Zend Engine, not any other implementation (such as HHVM, Hippy, Quercus, or JPHP ).
As of PHP 7.0, the official release of Zend Engine has always been implemented through the interpreter (*). The Zend bytecode commands are entered into the interpreter one by one, and the bytecode commands are executed by functions written in C Language corresponding to the opcode. That's simple.
Simple workflow:
[PHP source code]
=> Lexical analysis
/Syntax analysis
-> [Abstract syntax tree (AST)
]
=> Bytecode Compiler
-> [Zend bytecode (Instruction Set: Zend opcodes
)]
=> Bytecode Interpreter
-> [Program running result]
The specific interpreter is how to assign the opcode to its corresponding function. Zend Engine can be configured in several different ways: call threading, switch threading, computed goto threading. What are the meanings of these names? refer to this article: Threaded Code
Taking the simplest switch-threading as an example, the basic form of this interpreter is as follows:
while (TRUE) { int opcode = *program_counter; switch (opcode) { case ZEND_ADD: // execute add ... program_counter++; // next opcode break; case ZEND_SUB: // execute sub ... program_counter++; // next opcode break; // ... }}
PHP source code = (interpreter) => opcode (PHP: Zend Engine 2 Opcodes
, Understood as assembly) = (zend engine) => machine code a computer can only execute machine code, but it does not convert PHP Code directly into machine code for execution, but into a line of opcode, in fact, opcode corresponds to a C function. Executing an opcode is to execute the C function corresponding to this opcode, and this C function has been compiled as a machine code.