前置準備
- PHP 源碼包 (與目標版本一致)
- 編譯工具鏈:Linux (gcc, make, autoconf, automake, libtool),Windows (Visual Studio + PHP SDK)
- 基本 C 語言與 Zend API 知識
步驟詳解 (Linux 為例)
- 進入擴展目錄並生成骨架
cd php-src/ext
./ext_skel --extname=my_module
生成 my_module/ 目錄,包含 config.m4、my_module.c、php_my_module.h、測試腳本等。
- 編輯 config.m4 — 取消註釋啟用擴展的三行:
PHP_ARG_ENABLE(my_module, whether to enable my_module support,
[ --enable-my_module Enable my_module support])
if test "$PHP_MY_MODULE" != "no"; then
PHP_NEW_EXTENSION(my_module, my_module.c, $ext_shared)
fi
- 實現功能函數 — 編輯
my_module.c:
// 在文件末尾添加
PHP_FUNCTION(say_hello)
{
zend_printf("hello world\n");
}
- 聲明函數入口 — 編輯
php_my_module.h,在 PHP_FUNCTION(confirm_my_module_compiled); 前添加:
PHP_FUNCTION(say_hello);
- 註冊函數表 — 在
my_module.c 中 zend_function_entry my_module_functions[] 數組添加:
PHP_FE(say_hello, NULL)
- 構建配置並編譯:
cd ../.. # 回到 php-src 根目錄
./buildconf --force
./configure --enable-my_module
make
- 測試:
# 創建測試腳本 test.php
<?php say_hello(); ?>
# 運行
sapi/cli/php test.php
# 輸出: hello world
關鍵概念
zend_printf:Zend 內部輸出函數,直接寫入 SAPI 輸出流。
PHP_FUNCTION:展開為 void zif_say_hello(zend_execute_data *execute_data, zval *return_value)。
PHP_FE:生成函數條目結構體,供引擎查找調用。
- 參數解析:
ZEND_PARSE_PARAMETERS_START() / Z_PARAM_STRING() 等宏 (PHP 7+)。
- 內存管理:
emalloc/efree、引用計數 Z_ADDREF/Z_DELREF。
進階資源
- 官方文檔:PHP Internals Book
- 《PHP 7 內核剖析》—— TIPI 團隊
- 現有擴展源碼 (ext/standard、ext/json、ext/pdo 等) 是最佳教材。