Linux下編寫一個PHP擴展

假設需求javascript

開發一個叫作 helloWord 的擴展。php

擴展裏有一個函數,helloWord()。java

echo helloWord('Tom');
//返回:Hello World: Tom複製代碼

本地環境後端

PHP版本:5.6.9微信

系統:Linux CentOS release 6.5 (Final)函數

最終效果spa

實現流程code

第一步:cdn

進入到本地的php目錄執行:

cd /root/soft/src/php-5.6.9
cd ext
./ext_skel --extname=helloWord
cd helloWord
vi config.m4

搜索:dnl Otherwise use enable 將下面修改爲:

PHP_ARG_ENABLE(helloWorld, whether to enable helloWorld support,
[  --enable-helloWorld           Enable helloWorld support])

if test "$PHP_HELLOWORLD" != "no"; then

...複製代碼

如圖:blog

第二步:

vi php_helloWorld.h

搜索:extern zend_module_entry 新增一行:

PHP_FUNCTION(helloWorld);複製代碼

如圖:

第三步:

vi helloWorld.c

搜索:const zend_function_entry helloWorld_functions[] 新增一行:

PHP_FE(helloWorld, NULL)複製代碼

如圖:

搜索:PHP_MINFO_FUNCTION(helloWorld) 

新增版本、做者信息

php_info_print_table_row(2, "Version", "1.0");
php_info_print_table_row(2, "Author", "BiHu");複製代碼

如圖:

在 helloWorld.c 底部新增一個方法

PHP_FUNCTION(helloWorld)
{
    char *arg = NULL;
    int arg_len, len;
    char *strg;
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) {
        return;
    }
    len = spprintf(&strg, 0, "Hello World: %s", arg);
    RETURN_STRINGL(strg, len, 0);
}複製代碼

如圖:

第四步:

//編譯安裝
cd /root/soft/src/php-5.6.9/ext
/usr/local/php/bin/phpize #用phpize生成configure配置文件
./configure --with-php-config=/usr/local/php/bin/php-config   #配置
make  #編譯
make install  #安裝複製代碼

第五步:

//修改php.ini
extension="helloWorld.so"   #名稱爲安裝擴展的名稱複製代碼

第六步:

重啓環境。

完成上面的步驟,簡單的 helloWorld 擴展就OK了。

你們能夠根據本身的需求,開發知足本身的擴展。

好比,能夠開發一些擴展類,擴展方法,等等。

若是你們須要helloWorld擴展包,能夠關注微信公衆號。

回覆 「helloWorld」 便可。

Thanks ~


做者:PHP後端開發者

提供技術相關服務(本身懂的知識)。

QQ羣:564557094。

關注微信公衆號,留言便可,看到留言後會及時回覆。

IT小圈兒
相關文章
相關標籤/搜索