天天看點

編寫一個簡單的PHP擴充

轉自個人部落格:

https://www.tanchengjin.com/article/109

測試環境ubuntu:14.04

首先在php官網下載下傳php包

wget 
http://cn2.php.net/get/php-7.1.27.tar.gz/from/this/mirror      

下載下傳之後的包名位mirror 直接使用tar解壓即可

tar -zxvf mirror      

解壓後進入ext檔案夾

cd php-7.1.27/ext/      

利用.ext_skel生成項目骨架,并在目前目錄中生成helloWorld檔案夾

./ext_skel --extname=helloWorld      

提示生成擴充的步驟:

=======================================================

Creating directory helloWorld

Creating basic files: config.m4 config.w32 .gitignore helloWorld.c php_helloWorld.h CREDITS EXPERIMENTAL tests/001.phpt helloWorld.php [done].

To use your new extension, you will have to execute the following steps:

1.  $ cd ..

2.  $ vi ext/helloWorld/config.m4

3.  $ ./buildconf

4.  $ ./configure --[with|enable]-helloWorld

5.  $ make

6.  $ ./sapi/cli/php -f ext/helloWorld/helloWorld.php

7.  $ vi ext/helloWorld/helloWorld.c

8.  $ make

Repeat steps 3-6 until you are satisfied with ext/helloWorld/config.m4 and

step 6 confirms that your module is compiled into PHP. Then, start writing

code and repeat the last two steps as often as necessary.

=============================================================

進入項目檔案夾

cd helloWorld      

編輯config.m4檔案

vim config.m4      

去掉這兩行的dnl(dnl為注釋符,這段話是說如果此擴充依賴其他擴充,去掉

PHP_ARG_WITH

段的注釋符;否則去掉

PHP_ARG_ENABLE

段的注釋符。顯然我們不依賴其他擴充或lib庫,是以去掉

PHP_ARG_ENABLE

段的注釋符:)

編寫一個簡單的PHP擴充

編輯helloWorld.c檔案

vim helloWorld.c      

注釋掉自動生成的方法

編寫一個簡單的PHP擴充

重寫PHP_FUNCTION方法

編寫一個簡單的PHP擴充

添加到編譯清單裡,同時注釋掉confirm_helloWorld_compiled

編寫一個簡單的PHP擴充

讓zend引擎知道此子產品有什麼函數

儲存退出

執行phpize

phpize      
編寫一個簡單的PHP擴充

生成.so檔案

./configure --with-php-config=/usr/bin/php-config      
編寫一個簡單的PHP擴充

編譯

make && make install      
編寫一個簡單的PHP擴充

編譯成功後會在項目檔案夾/ext/helloWorld/modules下生成helloWorld.so檔案

編寫helloWorld.php檔案,寫入如下代碼

<?php
 echo helloWorld();
           

執行 

php helloWorld.php      

就可以看到執行結果

轉自個人部落格:

https://www.tanchengjin.com/article/109