本文通過編寫一個簡單的PHP擴充hello_world來說明PHP擴充是如何編寫的。這個擴充沒有任何的實用性,純粹用來學習擴充如何編寫的,如果真的想自己寫出實用性的PHP擴充,還需要熟悉ZEND API,而且對C語言也有較高的要求。
好,進入正題。
1、進入PHP源碼的ext目錄下,然後執行:
./ext_skel --extname=hello_world
2、進入hello_world目錄,編輯config.m4,去掉16行、18行和53行前面的dnl:
PHP_ARG_ENABLE(hello_world, whethertoenablehello_worldsupport,[ --enable-hello_world Enable hello_world support])AC_DEFINE(HAVE_HELLO_WORLDLIB,1,[ ])
3、修改php_hello_world.h檔案,把原來的
#define PHP_HELLO_WORLD_H
改為如下內容:
#define PHP_HELLO_WORLD_H 1#define PHP_HELLO_WORLD_VERSION "1.0"#define PHP_HELLO_WORLD_EXTNAME "hello_world"PHP_FUNCTION(hello_world);//這句最關鍵
4、修改hello_world.c檔案:
把如下內容:
const zend_function_entry hello_world_functions[] = { PHP_FE(confirm_hello_world_compiled, NULL) /* For testing, remove later. */ PHP_FE_END /* Must be the last line in hello_world_functions[] */};
改成:
const zend_function_entry hello_world_functions[] = { PHP_FE(confirm_hello_world_compiled, NULL) /* For testing, remove later. */ PHP_FE(hello_world, NULL) PHP_FE_END /* Must be the last line in hello_world_functions[] */};
然後在尾部加入如下內容:
//擴充函數本文部分PHP_FUNCTION(hello_world){ RETURN_STRING("Hello World!",1);}
5、到ext/hello_world目錄下執行如下命令
/usr/local/php/bin/phpize./configure --with-php-config=/usr/local/php/bin/php-configmake && make install
6、編輯php.ini,增加如下內容:
extension=hello_world.so
測試:
在命令列執行如下內容:
php -r"echo hello_world();"
這時候會在標準輸出那裡看到如下內容:
HelloWorld!
至此,hello_world擴充編寫完畢!
著作權聲明:本文為博主原創文章,轉載請註明出處。
以上就介紹了PHP擴充編寫入門,包括了方面的內容,希望對PHP教程有興趣的朋友有所協助。