PHP 擴展開發能將核心邏輯下沉到 C 層,大幅提升效能。本文詳細記錄在 Linux 環境下,從源碼目錄結構解析到完整編譯安裝的 Hello World 擴展開發全過程。
完成 LAMP 環境配置後,進入 PHP 源碼包 /ext 目錄,可見官方內置擴展(MySQL、XML 等)。建立獨立擴展目錄:
mkdir hello && cd hello
創建 config.m4 定義編譯選項:
PHP_ARG_ENABLE(hello, whether to enable Hello support,
[ --enable-hello Enable Hello support])
if test "$PHP_HELLO" = "yes"; then
AC_DEFINE(HAVE_HELLO, 1, [Whether you have Hello])
PHP_NEW_EXTENSION(hello, hello.c, $ext_shared)
fi
PHP_ARG_ENABLE:創建 --enable-hello 選項,第二參數顯示於 ./configure --helpPHP_NEW_EXTENSION:聲明源文件,多文件用空格分隔 PHP_NEW_EXTENSION(hello, hello.c hello2.c, $ext_shared)$ext_shared:構建共享模組時必需enable vs with:enable 可關閉,with 需第三方庫#ifndef PHP_HELLO_H #define PHP_HELLO_H #define PHP_HELLO_EXTNAME "hello" #define PHP_HELLO_EXTVER "1.0" #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" PHP_FUNCTION(hello_world); // 聲明導出函數 extern zend_module_entry hello_module_entry; #define phpext_hello_ptr &hello_module_entry #endif
php.h 必須引入zend_module_entry 聲明為 extern,使 Zend 能通過 dlopen()/dlsym() 定位模組入口#include "php_hello.h"
static function_entry hello_functions[] = {
PHP_FE(hello_world, NULL) // 導出到用戶空間
{NULL, NULL, NULL}
};
zend_module_entry hello_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
STANDARD_MODULE_HEADER,
#endif
PHP_HELLO_EXTNAME,
hello_functions,
NULL, /* MINIT */
NULL, /* MSHUTDOWN */
NULL, /* RINIT */
NULL, /* RSHUTDOWN */
NULL, /* MINFO */
#if ZEND_MODULE_API_NO >= 20010901
PHP_HELLO_EXTVER,
#endif
STANDARD_MODULE_PROPERTIES
};
#ifdef COMPILE_DL_HELLO
ZEND_GET_MODULE(hello)
#endif
/* 函數實現 */
PHP_FUNCTION(hello_world) {
php_printf("Hello World!\n");
}
function_entry:函數表,將 C 函數映射到 PHP 用戶空間zend_module_entry:模組入口,定義生命周期鉤子(MINIT/RINIT/MSHUTDOWN/RSHUTDOWN/MINFO)ZEND_GET_MODULE:動態加載時的入口導出PHP_FUNCTION 宏:標準化函數簽名,處理參數解析、返回值phpize ./configure --enable-hello make sudo make install
php.ini 添加 extension=hello.sosudo /etc/init.d/httpd restartphpinfo() 檢查 hello 模組是否載入<?php hello_world(); // 輸出: Hello World! ?>
成功輸出即表示擴展開發完成。此為所有 PHP C 擴展開發的基礎模板,後續可擴展複雜邏輯、類封裝、資源管理等高級特性。