首頁 >後端開發 >php教程 >PHP7擴充開發之hello word實作方法

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

小云云
小云云原創
2018-01-16 13:45:331863瀏覽

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

這裡是以PHP7為基礎,講解如何從零開始建立一個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 [ --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])

#第三步,程式碼實作

##csay. 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方法。 #PHP7中新特性簡介

PHP7錯誤處理與異常處理方法

搭建php7的效能測試環境的方法

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

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