动态加载so模块:利用ext_skel工具编译生成so模块,修改php.ini文件,动态加载即可
静态编译:将编写的模块静态编译到PHP,需要重新编译PHP
假设要编写一个my_dynamic扩展,调用my_dynamic函数后输出字符串“The Best or Nothing”
echo my_dynamic();
?>
输出:
$ php . /test .php
$ The Best or Nothing
环境约定:
a.为了方便,安装过程均使用root用户;
b.PHP安装目录:/usr/local/php7
c.PHP源码:/usr/local/src/php-7.0.9
[root@bogon xuj]# cd /usr/local/src/php-7.0.9/ext/
[root@bogon ext]# ./ext_skel --extname=my_dynamic
这里会在/usr/local/src/php-7.0.9/ext/目录下生成my_dynamic扩展的目录,
同时也可以看到ext_skel提示的编译流程,这里也可以参考laruence前辈给出的PHP extension步骤
ext_skel:
laruence:
2.修改config.m4
[root@bogon ext]# cd my_dynamic/
[root@bogon my_dynamic]# vi config.m4
去掉dnl
dnl PHP_ARG_WITH(my_dynamic, for my_dynamic support,
dnl Make sure that the comment is aligned:
dnl [ --with-my_dynamic Include my_dynamic support])
去掉dnl后:
PHP_ARG_WITH(my_dynamic, for my_dynamic support,
dnl Make sure that the comment is aligned:
[ --with-my_dynamic Include my_dynamic support])
3.编写my_dynamic函数
[root@bogon my_dynamic]# vi my_dynamic.c
插入:
PHP_FUNCTION(my_dynamic)
{
php_printf("The Best or Nothing\n");
RETURN_TRUE;
}
在const zend_function_entry my_dynamic_functions 插入 PHP_FE(my_dynamic,NULL)
4.编译安装扩展
[root@bogon my_dynamic]# /usr/local/php7/bin/phpize
[root@bogon my_dynamic]# ./configure --with-php-config=/usr/local/php7/bin/php-config 根据自己环境写php-config路径
[root@bogon my_dynamic]# make && make install
成功生成扩展 在目录:/usr/local/php7/lib/php/extensions/no-debug-non-zts-20151012/
可以去no-debug-non-zts-20151012目录查看
5. 修改php.ini文件
加入
[my_dynamic]
;just test 20161020
extension=my_dynamic.so
[root@bogon no-debug-non-zts-20151012]# /usr/local/src/php-7.0.9/sapi/cli/php -m|grep my
6.测试
编写测试文件test.php
[root@bogon my_dynamic]#vi test.php
echo my_dynamic();
?>
测试
[root@bogon my_dynamic]# /usr/local/src/php-7.0.9/sapi/cli/php test.php
可以看到PHP能正常调用my_dynamic扩展,输出期望的The Best or Nothing
[PHP扩展开发之动态加载so模块与静态重编译PHP(下)](http://blog.csdn.net/xujunabc999/article/details/52870880)
参考:
用C/C++扩展你的PHP http://www.laruence.com/2009/04/28/719.html
centOS6.6 编译安装lnmp(PHP 7.0.9+Nginx1.9.9+MySQL5.7.15) http://blog.csdn.net/xujunabc999/article/details/52588145