php7中如何创建扩展

发布时间:2021-08-03 09:44:38 作者:小新
来源:亿速云 阅读:133

这篇文章将为大家详细讲解有关php7中如何创建扩展,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

将实现如下功能:

<?phpecho say();
?>

输出内容:

$ php ./test.php
$ hello word

在扩展中实现一个say方法,调用say方法后,输出 hello word。

第一步:生成代码

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

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

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

第二步,修改config.m4配置文件

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

$ cd ./say
$ 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.c文件。实现say方法。
找到PHP_FUNCTION(confirm_say_compiled),在其上面增加如下代码:

PHP_FUNCTION(confirm_say_compiled)
{
        zend_string *strg;
        strg = strpprintf(0, "hello word");
        RETURN_STR(strg);
}

找到 PHP_FE(confirm_say_compiled, 在上面增加如下代码:

PHP_FE(say, NULL)

修改后的代码如下:

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

第四步,编译安装

编译扩展的步骤如下:

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

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

[say]
extension = say.so

然后执行,php -m 命令。在输出的内容中,你会看到say字样。

第五步,调用测试

自己写一个脚本,调用say方法。看输出的内容是否符合预期。

关于“php7中如何创建扩展”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

推荐阅读:
  1. PHP7安装扩展
  2. php7安装redis扩展和memcache扩展

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php7

上一篇:css中background-attachment属性有什么用

下一篇:Ubuntu系统启动后怎么还原上次运行的应用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》