PHP7 扩展开发方法详解

2,537 阅读2分钟

本文开发环境为php7,从零开始创建一个PHP扩展,实现一个自定义函数say_hi,调用此函数返回Hello World。开始开发前请先安装php7及下载一份php7源码

一 生成代码

PHP提供了生成基本代码的工具 ext_skel,这个工具在PHP源代码的./ext目录下

$ cd php_src/ext/
$ ./ext_skel --extname=say_hi

extname参数的值就是扩展名称,执行ext_skel命令后,会在当前目录下会生成一个与扩展名一样的目录。

二 修改config.m4配置文件

config.m4的作用是配合phpize工具生成configure文件(onfigure文件是用于检测扩展编译运行所需的环境是否满足),现在开始修改config.m4文件

$ cd ./say_hi
$ vim ./config.m4

config.m4文件有这样一段文字

dnl If your extension references something external, use with:
   
dnl PHP_ARG_WITH(say, for say support,
dnl Make sure that the comment is aligned:
dnl [  --with-say             Include say support])
 
dnl Otherwise use enable:
 
dnl PHP_ARG_ENABLE(say, whether to enable say support,
dnl Make sure that the comment is aligned:
dnl [  --enable-say           Enable say support])

其中,dnl 是注释符号,上面的代码意思是如果你所编写的扩展依赖其它的扩展或者lib库,需要去掉PHP_ARG_WITH相关代码的注释。否则,去掉 PHP_ARG_ENABLE 相关代码段的注释。我们编写的扩展不需要依赖其他的扩展和lib库。因此,我们去掉PHP_ARG_ENABLE前面的注释。去掉注释后的代码如下:

dnl If your extension references something external, use with:
    
 dnl PHP_ARG_WITH(say, for say support,
 dnl Make sure that the comment is aligned:
 dnl [  --with-say             Include say support])
  
 dnl Otherwise use enable:
  
 PHP_ARG_ENABLE(say, whether to enable say support,
 Make sure that the comment is aligned:
 [  --enable-say           Enable say support])

三 实现扩展方法

修改say_hi.c文件来实现say_hi方法,找到PHP_FUNCTION(confirm_say_hi_compiled),在其上面增加如下代码:

PHP_FUNCTION(say_hi)
{
        zend_string *strg;
        strg = strpprintf(0, "Hello World");
        RETURN_STR(strg);
}

找到 PHP_FE(confirm_say_hi_compiled,NULL), 在上面增加如下代码:

PHP_FE(say_hi, NULL)

修改后的代码如下:

const zend_function_entry say_functions[] = {
     PHP_FE(say_hi, NULL)       
     PHP_FE(confirm_say_hi_compiled,    NULL)       /* For testing, remove later. */
     PHP_FE_END  /* Must be the last line in say_functions[] */
 };
 /* }}} */

四 编译安装写好的扩展

$ phpize
$ ./configure
$ make && make install

修改php.ini文件,增加如下代码:

extension = say_hi.so

然后执行php -m命令查看已安装扩展,在输出的内容中如果有say_hi则说明安装成功

五 测试

写一个脚本test.php,假如放在home目录,内容如下:

然后执行:

php ~/test.php

输出Hello World,扩展编写成功