目前,PHP編程語言也是相當成熟,各種文檔,各種問題,只要Google一下,總有你想要的答案。當然“如何開發PHP擴展”的文章也不少,但是很少有專門來介紹使用C++開發PHP擴展的介紹。C++編程語言功能的強大,促使好多公司后台程序選擇使用它,因此碰到的大多數情況是需要我們用C++來擴展 PHP。PHP源碼中的擴展骨架工具,默認生成的是支持 C 語言,如果要使用C++開發,有些參數需要另行配置。下面將用一個簡單的示例來說明。
准備工作:
1. 下載PHP源碼 http://www.php.net/downloads,這里下載到的是 php-5.3.24.tar.gz
2. 解壓后,源碼放到 /root/php-5.3.24/
3. 安裝目錄:/usr/local/php-5.3.24/
4. 開始安裝,配置 php.ini 的路徑,方便以后進行個性化配置
5. 擴展名稱:discuz
6. 擴展函數:discuz_say(),這個函數只返回一個“Hello world!” 字符串
7. 擴展可運行在 win32 系統,也運行在類unix系統,但是需要編譯不同的文件,這里只介紹 GNU/Linux 下的操作。
開始編寫擴展:
1. 創建要實現的函數列表文件 discuz.proto,內容如下:
string discuz_say()
2. 使用擴展骨架工具生成核心文件,命令如下:
[root@localhost ~]# cd php-5.3.24/ext/ [root@localhost ext]# ./ext_skel --extname=discuz --proto=../../discuz.proto
這時就在 ext 目錄下出現了 discuz 文件夾,里面包含幾個文件,如:config.m4 discuz.c php_discuz.h 等等。
3. 修改config.m4文件,內容如下:
dnl $Id$ dnl config.m4 for extension discuz PHP_ARG_ENABLE(discuz, whether to enable discuz support, Make sure that the comment is aligned: [ --enable-discuz Enable discuz support]) if test "$PHP_DISCUZ" != "no"; then PHP_REQUIRE_CXX() dnl 通知Make使用g++ PHP_ADD_LIBRARY(stdc++, 1, EXTRA_LDFLAGS) dnl 加入C++標准庫 PHP_NEW_EXTENSION(discuz, discuz.cpp, $ext_shared) fi
這個文件中 dnl 是注釋符,其之后的字串是解釋上下文。
4. 修改 discuz.c 文件重名為 discuz.cpp(這樣命名看起來更專業)
4.1 加入需要的C++ string 頭文件,如下:
#ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "php_discuz.h" #include <string> /* 添加這行 */
4.2 修改 discuz_say 函數,如下:
/* {{{ proto string discuz_say() */ PHP_FUNCTION(discuz_say) { std::string str = "Hello world!"; RETURN_STRINGL(str.c_str(), str.length(), 1); }
5. 編譯擴展,把其 discuz.so 放到安裝目錄(可以參考 編譯PHP擴展的兩種方式)。
開始測試:
<?php echo discuz_say() . "\n"; ?>
[root@localhost ~]# /usr/local/php-5.3.24/bin/php hi.php Hello world!到此,一個簡單的擴展就完成了