Backend Development 16 min read

Understanding PHP Execution: Zend VM Process, Opcodes, and Opcache

This article explains how PHP code is compiled and executed by the Zend virtual machine, detailing the four compilation stages, the structure of opcodes and execution data, the different dispatch mechanisms, and the role of Opcache in improving performance.

Beike Product & Technology
Beike Product & Technology
Beike Product & Technology
Understanding PHP Execution: Zend VM Process, Opcodes, and Opcache

The article begins by outlining the four compilation stages of a C program—pre‑processing, compilation, assembly, and linking—and maps these concepts to PHP, where source code is first tokenised, then parsed into an abstract syntax tree (AST) before being compiled into an op_array of opcodes.

It then describes the PHP implementation, explaining that the Zend VM (ZendVM) interprets the op_array using a set of handlers. Each opcode (opline) is defined by a zend_op structure, and the possible operand types are enumerated as IS_CONST , IS_TMP_VAR , IS_VAR , IS_UNUSED , and IS_CV . Example handler code for the ADD opcode shows how different operand type combinations select different specialised functions.

The execution process is broken into four steps: (1) creating a new zend_execute_data frame with zend_vm_stack_push_call_frame , (2) initializing the frame via i_init_code_execute_data which attaches the symbol table and loads runtime caches, (3) running a loop that dispatches each opcode using one of four dispatch modes (CALL, SWITCH, GOTO, HYBRID) – the default being CALL – and handling the four possible return codes ( ZEND_VM_ENTER , ZEND_VM_LEAVE , ZEND_VM_RETURN , ZEND_VM_CONTINUE ), and (4) freeing the call frame, which is actually cached for reuse.

Finally, the article discusses Opcache, the shared‑memory extension that stores compiled zend_persistent_script structures to avoid recompilation on each request. It outlines the structure of the cached script, the initialization of the extension via accel_startup , and the workflow of retrieving or generating the cache.

Backend DevelopmentPHPOpCacheopcodeszend-vm
Beike Product & Technology
Written by

Beike Product & Technology

As Beike's official product and technology account, we are committed to building a platform for sharing Beike's product and technology insights, targeting internet/O2O developers and product professionals. We share high-quality original articles, tech salon events, and recruitment information weekly. Welcome to follow us.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.