一、下載源碼。
先到官網下載PHP的原始碼,這裡我用的是PHP5.3.5
開啟我們可以看到ext這個目錄這目錄是放所有的擴充的。在改目錄下我們可以看到ext_skel的指令碼下面我就用這個命令來產生擴充的基本架構。
二、建立基本架構
./ext_skel --extname=example
這個命令會在ext目錄下產生一個example目錄,改目錄下有以下檔案
#在目錄下有不少檔案,testmodule.c 和 config.m4 是最重要的example.c #是我們擴充的主要檔案config.m4 #m4是一個宏解釋工具,用來產生我們擴充的makefileCREDITES #這個檔案沒什麼太大的作用,只是用來在發布你的擴充的時候附加一些其他資訊EXPERIMENTAL #這個檔案只是標誌說,這個擴充是實驗性的,所以可以不用管它php_example.h #這個是我們擴充的標頭檔tests/001.phpt #這個也是個測試檔案,不過使用的是單元測試,階段測試
三、實現。
1、修改設定檔config.m4,去掉前面的dnl(dnl在m4檔案裡表注釋)
vi config.m4PHP_ARG_ENABLE(example, whether to enable laiwenhui support,[ --enable-laiwenhui Enable laiwenhui support])# PHP_ARG_WITH(testmodule, for testmodule support,# Make sure that the comment is aligned:# --with-testmodule Include testmodule support]) # 這裡的with是說明,要啟用這個模組,依賴於某些其他模組,這裡我們可以暫時不管。# 比如:模組example,如果依賴apxs的話,就需要:# /configure --with-apxs=/usr/local/apache/bin/apxs --enable-example
2、聲明函數
在檔案php_example.h檔案中編輯
vi php_example.h
我們找到PHP_FUNCTION(confirm_example_compiled); 在其後面添加PHP_FUNCTION(test);
3、實現函數test
vi example.c
把下面代碼寫到最後面
/** * 我添加的第一個PHP擴充 * * */PHP_FUNCTION(test){ char *str = NULL; char *arg = NULL; int arg_len; int len;// str = "Hello my first php extention! ^_^";
//len = strlen(str);
//RETURN_STRINGL(str, len, 0);
//開始想這樣寫的可以沒效果,不知道為什麼不行。難道不支援strlen但是能編譯通過。 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) { return; } len = spprintf(&str, 0, "Hello my first php extention! ^_^ param %s",arg); RETURN_STRINGL(str, len, 0);}
spprintf應該是php的函數。
zend_parse_parameters是PHP的一個函數表示取得參數解析,如果失敗返回。
4、告訴zend引擎這個example模組中有哪些函數。
找到:zend_function_entry testmodule_functions[]這一行,注釋的意思是:所有可用的函數必須要在這裡面定義。
修改為:
* Every user visible function must have an entry in example_functions[]. */const zend_function_entry example_functions[] = { PHP_FE(confirm_example_compiled, NULL) /* For testing, remove later. */ PHP_FE(test, NULL) /* 我的擴充test */ {NULL,NULL, NULL} /* Must be the last line in example_functions[] */};/* }}}
5、編譯
進入example模組
./configure ?with-php-config=/usr/local/php/bin/php-config
/usr/local/php/bin/phpize
make
cp modules/example.so /usr/local/php/lib/php/extensions/
然後修改php.ini,讓example.so啟用,最後重啟Web服務
四、測試。
這裡有篇鳥哥的文章解釋的更清楚。
http://www.laruence.com/2009/04/28/719.html