课程进度 73% · 第17/22章第17/22章 · 标签 1/6
— 1 —
PHP内核
Zend引擎是PHP的核心,负责解析和执行PHP代码。PHP变量在内部使用zval结构体表示,包含值、类型信息和附加字段。
- 词法分析:将代码拆分为token
- 语法分析:构建抽象语法树(AST)
- 编译:AST编译为opcode
- 执行:Zend引擎执行opcode
c
1
typedef struct _zval_struct {
2
zend_value value; // 值
3
union {
4
struct {
5
ZEND_ENDIAN_LOHI_4(
6
zend_uchar type, // 类型
7
zend_uchar type_flags, // 类型标志
8
zend_uchar const_flags, // 常量标志
9
zend_uchar reserved) // 保留字段
10
} v;
11
uint32_t type_info;
12
} u1;
13
union {
14
uint32_t next; // 哈希表冲突链
15
uint32_t cache_slot; // 缓存槽
16
uint32_t lineno; // 行号
17
uint32_t num_args; // 参数数量
18
uint32_t fe_pos; // foreach位置
19
uint32_t fe_iter_idx; // foreach迭代器索引
20
} u2;
21
} zval;
— 2 —
类型系统与引用计数
PHP类型系统定义了11种变量类型,使用引用计数管理内存。
c
1
2
3
4
5
6
7
8
9
10
11
12
13
// PHP使用引用计数进行内存管理
14
static zend_always_inline void zval_add_ref(zval* pz) {
15
if (Z_REFCOUNTED_P(pz)) {
16
Z_REFCOUNT_P(pz)++;
17
}
18
}
19
20
// 垃圾回收
21
static void gc_collect_cycles(void) {
22
// 收集循环引用
23
// 释放内存
24
}
Zend引擎ASTopcodeGC引用计数