课程进度 73% · 第17/22章第17/22章 · 标签 1/6
— 1 —
PHP内核
Zend引擎是PHP的核心,负责解析和执行PHP代码。PHP变量在内部使用zval结构体表示,包含值、类型信息和附加字段。
- 词法分析:将代码拆分为token
- 语法分析:构建抽象语法树(AST)
- 编译:AST编译为opcode
- 执行:Zend引擎执行opcode
```c
typedef struct _zval_struct {
zend_value value; // 值
union {
struct {
ZEND_ENDIAN_LOHI_4(
zend_uchar type, // 类型
zend_uchar type_flags, // 类型标志
zend_uchar const_flags, // 常量标志
zend_uchar reserved) // 保留字段
} v;
uint32_t type_info;
} u1;
union {
uint32_t next; // 哈希表冲突链
uint32_t cache_slot; // 缓存槽
uint32_t lineno; // 行号
uint32_t num_args; // 参数数量
uint32_t fe_pos; // foreach位置
uint32_t fe_iter_idx; // foreach迭代器索引
} u2;
} zval;
```
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
#define IS_UNDEF 0
#define IS_NULL 1
#define IS_FALSE 2
#define IS_TRUE 3
#define IS_LONG 4
#define IS_DOUBLE 5
#define IS_STRING 6
#define IS_ARRAY 7
#define IS_OBJECT 8
#define IS_RESOURCE 9
#define IS_REFERENCE 10
// PHP使用引用计数进行内存管理
static zend_always_inline void zval_add_ref(zval* pz) {
if (Z_REFCOUNTED_P(pz)) {
Z_REFCOUNT_P(pz)++;
}
}
// 垃圾回收
static void gc_collect_cycles(void) {
// 收集循环引用
// 释放内存
}
```
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引用计数