Home >Backend Development >PHP Tutorial >PHP extension and embedding--c extension development helloworld_PHP tutorial
After completing the LAMP configuration environment under Linux, you can proceed with PHP extension development.
Extension development in PHP is under the /ext folder of the source code package. You can see that there are many developed extensions here. For example, database-related mysql and xml processing modules, etc.
First create a folder:
mkdir hello
After entering this folder, first create and open a configuration file:
vim config.m4
This gives an example of a configuration problem:
1 PHP_ARG_ENABLE(sample, whether to enable SAMPLE support, 2 [ --enable-sample Enable SAMPLE support]) 3 if test "$PHP_SAMPLE" = "yes"; then 4 AC_DEFINE(SAMPLE, 1, [Whether you have SAMPLE]) 5 PHP_NEW_EXTENSION(sample, sample.c, $ext_shared) 6 fi* This configuration file creates a --enable-hello configuration option, and the second option of PHP_ARG_ENABLE will be displayed during configuration
1 ?#ifndef PHP_SAMPLE_H 2 /* 防止两次引入 */ 3 #define PHP_SAMPLE_H 4 /* 定义扩展的性质 */ 5 #define PHP_SAMPLE_EXTNAME "sample" 6 #define PHP_SAMPLE_EXTVER "1.0" 7 /* 当在php的源码树之外build的时候,引入配置选项, 在使用phpize工具时,一般都是先定义的 */ 8 #ifdef HAVE_CONFIG_H 9 #include "config.h" 10 #endif 11 /* 引入php标准头文件 */ 12 #include "php.h" 13 PHP_FUNCTION(hello_world);//声明扩展中的函数 14 /* 定义入口点的符号,zend在加载这个module的时候会用*/ 15 extern zend_module_entry sample_module_entry; 16 #define phpext_sample_ptr &sample_module_entry 17 #endif /* PHP_SAMPLE_H */Finally, note two points: * php.h must be imported
#include "php_sample.h" static function_entry php_sample_functions[] = { PHP_FE(sample_hello_world, NULL)//任何扩展中的函数都要在这里声明。把函数名输出到了用户空间中 { NULL, NULL, NULL } }; zend_module_entry sample_module_entry = { //创建一个入口 #if ZEND_MODULE_API_NO >= 20010901 //这个是一个版本号 STANDARD_MODULE_HEADER, #endif PHP_SAMPLE_EXTNAME, php_sample_functions, /* Functions 这里是把php_function加入到Zend中去*/ NULL, /* MINIT */ NULL, /* MSHUTDOWN */ NULL, /* RINIT */ NULL, /* RSHUTDOWN */ NULL, /* MINFO */ #if ZEND_MODULE_API_NO >= 20010901 PHP_SAMPLE_EXTVER, #endif STANDARD_MODULE_PROPERTIES }; #ifdef COMPILE_DL_SAMPLE ZEND_GET_MODULE(sample) #endif //这块区域是当扩展被动态加载的时候,为Zend添加一个引用,记得要添加上就行。 /*真正的函数体的部分*/ PHP_FUNCTION(sample_hello_world) { php_printf("Hello World!\n"); }This is the content of the source code.
<?php sample_hello_world(); ?>If "Hello World!" is printed, it means that the php extension has been developed successfully.