PHP7擴充開發之hello word實作方法的詳解

jacklove
發布: 2023-04-02 07:54:01
原創
1497 人瀏覽過

這篇文章主要介紹了PHP7擴展開發之hello word實現方法,結合實例形式分析了php7擴展開發的具體步驟與相關操作技巧,涉及針對php底層源碼的修改與編譯,需要的朋友可以參考下

本文實例講述了PHP7擴充開發之hello word實作方法。分享給大家供大家參考,具體如下:

這裡是以PHP7作為基礎,講解如何從零開始創建一個PHP擴充。本文主要講解創建一個擴充的基本步驟有哪些。在範例中,我們將實作如下功能:

登入後複製

#輸出內容:

$ php ./test.php
$ hello word
登入後複製

##在擴充中實作一個say方法,呼叫say方法後,輸出hello word。

第一步:產生程式碼

PHP為我們提供了產生基本程式碼的工具

ext_skel#。這個工具在PHP原始碼的./ext目錄下。

$ cd php_src/ext/
$ ./ext_skel --extname=say
登入後複製

extname參數的值就是擴充名稱。執行ext_skel指令後,這樣在目前目錄下會產生一個與副檔名相同的目錄。

第二步,修改config.m4設定檔

#config.m4的功能就是配合phpize工具產生configure檔。 configure檔案是用於環境檢測的。檢測擴展編譯運行所需的環境是否滿足。現在我們開始修改config.m4檔。

$ cd ./say
$ vim ./config.m4
登入後複製

打開,config.m4檔案後,你會發現這樣一段文字。

dnl If your extension references something external, use with:
dnl PHP_ARG_WITH(say, for say support,
dnl Make sure that the comment is aligned:
dnl [ --with-say       Include say support])
dnl Otherwise use enable:
dnl PHP_ARG_ENABLE(say, whether to enable say support,
dnl Make sure that the comment is aligned:
dnl [ --enable-say      Enable say support])
登入後複製

其中,dnl 是註解符號。上面的程式碼說,如果你所寫的擴充功能如果依賴其它的擴充功能或lib函式庫,需要去掉

PHP_ARG_WITH相關程式碼的註解。否則,去掉 PHP_ARG_ENABLE 相關程式碼段的註解。我們寫的擴充不需要依賴其他的擴充功能和lib函式庫。因此,我們去掉PHP_ARG_ENABLE前面的註解。去掉註解後的程式碼如下:

dnl If your extension references something external, use with:
 dnl PHP_ARG_WITH(say, for say support,
 dnl Make sure that the comment is aligned:
 dnl [ --with-say       Include say support])
 dnl Otherwise use enable:
 PHP_ARG_ENABLE(say, whether to enable say support,
 Make sure that the comment is aligned:
 [ --enable-say      Enable say support])
登入後複製

#第三步,程式碼實作##修改say.c檔。實現say方法。

找到

PHP_FUNCTION(confirm_say_compiled)
,在上面增加如下程式碼:

PHP_FUNCTION(say)
{
    zend_string *strg;
    strg = strpprintf(0, "hello word");
    RETURN_STR(strg);
}
登入後複製

##找到

PHP_FE(confirm_say_compiled

#, 在上面增加如下程式碼:

PHP_FE(say, NULL)
登入後複製

修改後的程式碼如下:

const zend_function_entry say_functions[] = {
   PHP_FE(say, NULL)    /* For testing, remove later. */
   PHP_FE(confirm_say_compiled,  NULL)    /* For testing, remove later. */
   PHP_FE_END /* Must be the last line in say_functions[] */
 };
 /* }}} */
登入後複製

第四步,編譯安裝

#編譯擴充的步驟如下:

$ phpize
$ ./configure
$ make && make install
登入後複製

#修改php.ini文件,增加如下程式碼:

[say]
extension = say.so
登入後複製

#然後執行,

php -m

指令。在輸出的內容中,你會看到say字樣。

第五步,呼叫測試

#自己寫一個腳本,呼叫say方法。看輸出的內容是否符合預期。

您可能感興趣的文章:

PHP擴充開發之基於函數方式使用lib函式庫的方法詳解


thinkphp 中的volist標籤在ajax操作中的特殊性


詳解thinkphp中的volist標籤的解說


#

以上是PHP7擴充開發之hello word實作方法的詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!