首頁  >  文章  >  後端開發  >  教你一步一步來創建一個php擴充(基本步驟)

教你一步一步來創建一個php擴充(基本步驟)

不言
不言原創
2018-08-28 11:57:101779瀏覽

這篇文章帶給大家的內容是關於教你一步一步來創建一個php擴充(基本步驟) ,有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

建立一個擴充的基本步驟都有哪些。在範例中,我們將實作如下功能:

<?php
echo say();
?>

輸出內容:

$ 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 [  -dnl [  -dnl -with-say             Include say support])

dnl Otherwise use enable:

dnl PHP_ARG_ENABLE(say, whether to enable say support,#dnl PHP_ARG_ENABLE(say, whether to enable say support,#dnl PHP_ARG_ENABLE(say, whether to enable say support,#dnl PHP#dnl sure that alignment. ##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:

PHP_ARG_ENABLE(say, whether to enable supether, enable#. 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擴展之創建一個類別- orlion

從零開始創建一個PHP 擴充功能

#

以上是教你一步一步來創建一個php擴充(基本步驟)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn