前言
这是一篇拖了很久就想写的备忘录,编写php扩展一百度都是文章,但是很多文章是很老的了。有的例子都跑不通。有点尴尬。
此文用于记录自己的笔记,当作备忘录。
正文1. 下载php安装包下载地址:php下载快链
本文选取的是php-5.6.7安装包。
之后安装php。
2. 创建扩展骨架//跑到ext目录cd php-5.6.7/ext///执行一键生成骨架的操作./ext_skel --extname=helloworld
如果看到以下提示说明创建成果
cd helloworld
ls
一下你会发现有如下文件:
config.m4 config.w32 credits experimental helloworld.c helloworld.php php_helloworld.h tests
3. 修改扩展的配置文件config.m4去掉下面代码之前的dnl 。(dnl相当于php的//)
##动态编译选项,通过.so的方式链接,去掉dnl注释php_arg_with(helloworld, for helloworld support,
make sure that the comment is aligned:
[ --with-helloworld include helloworld support])##静态编译选项,通过enable来启用,去掉dnl注释php_arg_enable(helloworld, whether to enable helloworld support,
make sure that the comment is aligned:
[ --enable-helloworld enable helloworld support])
一般二者选一即可(看个人喜好吧,本文教程必须去掉enable的注释)。
4. 进行编译测试phpize
./configure --enable-helloworldmakemake install
然后到php.ini添加一下扩展
vim /usr/local/php/etc/php.ini// 添加扩展extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20131226/"extension = "helloworld.so"// 重启php-fpm/etc/init.d/php-fpm restart
回到写扩展的文件夹,执行测试命令
php -d enable_dl=on myfile.php
看到如下字样说明离胜利不远了:
confirm_helloworld_compiled
congratulations! you have successfully modified ext/helloworld/config.m4. module helloworld is now compiled into php.
confirm_helloworld_compiled是ext_skel自动生成的测试函数。
ps:如果本地安装了两个php版本,并且是用php7编写扩展的话,可能会遇到以下问题:
/mydata/src/php-7.0.0/ext/helloworld/helloworld.c: 在函数‘zif_confirm_helloworld_compiled’中:
/mydata/src/php-7.0.0/ext/helloworld/helloworld.c:58: 错误:‘zend_string’未声明(在此函数内第一次使用)
/mydata/src/php-7.0.0/ext/helloworld/helloworld.c:58: 错误:(即使在一个函数内多次出现,每个未声明的标识符在其
/mydata/src/php-7.0.0/ext/helloworld/helloworld.c:58: 错误:所在的函数内也只报告一次。)
/mydata/src/php-7.0.0/ext/helloworld/helloworld.c:58: 错误:‘strg’未声明(在此函数内第一次使用)
原因:编译的环境不是php7。
解决办法:php5 里面没有zend_string类型,用 char 替换,或者,修改你的php版本环境到php7
5. 创建helloworld函数编辑helloworld.c,补充要实现的函数
##zend_function_entry helloworld_functions 补充要实现的函数const zend_function_entry helloworld_functions[] = {
php_fe(confirm_helloworld_compiled, null) /* for testing, remove later. */
php_fe(helloworld, null) /* 这是补充的一行,尾巴没有逗号 */
php_fe_end /* must be the last line in helloworld_functions[] */};
找到”php_function(confirm_helloworld_compiled)”,另起一个函数编写函数实体:
php_function(helloworld) { php_printf("hello world!\n");
return_true;
}
再走一遍编译:
./configure --enable-helloworld && make && make install
测试一下是不是真的成功了:
php -d enable_dl=on -r "dl('helloworld.so');helloworld();"//输出hello world!
成功!
以上就是php扩展之关于hello world的详细介绍的详细内容。