天天看點

Linux 下編寫一個 PHP 擴充

    假設需求

開發一個叫做 helloWord 的擴充。

擴充裡有一個函數,helloWord()。

echo helloWord('Tom');
    //傳回:Hello World: Tom
      

    本地環境

PHP版本:5.6.9

系統:Linux CentOS release 6.5 (Final)

    最終效果

Linux 下編寫一個 PHP 擴充

    實作流程

第一步:

    進入到本地的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
     
    ...
      

如圖:

Linux 下編寫一個 PHP 擴充

第二步:

vi php_helloWorld.h
     
    搜尋:extern zend_module_entry 新增一行:
     
    PHP_FUNCTION(helloWorld);
      
Linux 下編寫一個 PHP 擴充

第三步:

vi helloWorld.c
     
    搜尋:const zend_function_entry helloWorld_functions[] 新增一行:
     
    PHP_FE(helloWorld, NULL)
      
Linux 下編寫一個 PHP 擴充
在 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);
    }
      
Linux 下編寫一個 PHP 擴充

第四步:

//編譯安裝
    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了。

大家可以根據自己的需求,開發滿足自己的擴充。

比如,可以開發一些擴充類,擴充方法,等等。

繼續閱讀