Home  >  Article  >  Backend Development  >  PHP扩展开发详细教程

PHP扩展开发详细教程

WBOY
WBOYOriginal
2016-06-20 13:01:351003browse

在几种情况下,我们会需要进行PHP扩展开发:

1、PHP本身无法访问的资源或是调用,

2、通过扩展的方式可以实现处于性能和效率的考虑,

3、用C实现会更好

4、处于商业或代码保护考虑,将代码封装起来

5、为了更深入的了解PHP,从这里入门

假设有这么一个扩展,提供一个叫ccvita_string的函数。下面详细介绍怎么样制作这样一个PHP扩展:

第一步、生成代码

PHP为了扩展开发的方便,提供了一个类似代码生成器的工具ext_skel,具体可以参见说明。
首先我们创建一个文件scutephp.skel,它的内容为
string scutephp_string(string str)

就是告诉ext_skel这个东西,我们要做的扩展里面有个函数叫scutephp_string。然后执行
cd usr/src/php-5.3.8/ext/<br />./ext_skel --extname=scutephp --proto=scutephp.skel<br />cd scutephp/

这时候,ccvita这个扩展的代码框架就已经出来了。

第二步、修改配置

然后修改config.m4文件将10、11、12三行最前面的dnl删除掉,就是将
dnl PHP_ARG_WITH(ccvita, for ccvita support,<br />dnl Make sure that the comment is aligned:<br />dnl [  --with-scutephp            Include scutephp support])

修改为
PHP_ARG_WITH(scutephp, for scutephp support,<br />Make sure that the comment is aligned:<br />[  --with-scutephp             Include scutephp support])

第三步、实现功能

修改源码scutephp.c文件
找到将scutephp_string这个函数修改为
PHP_FUNCTION(scutephp_string)<br />{<br />    char *str = NULL;<br />    int argc = ZEND_NUM_ARGS();<br />    int str_len;<br />    char *result;<br /><br />    if (zend_parse_parameters(argc TSRMLS_CC, "s", &str, &str_len) == FAILURE) <br />        return;<br /><br />    str_len = spprintf(&result, 0, "<a href="%.78s">Link</a>", str);<br />    RETURN_STRINGL(result, str_len, 0); <br />}

第四步、编译扩展

保存后,开始编译
/usr/local/php/bin/phpize<br />./configure --with-php-config=/usr/local/php/bin/php-config<br />make

第五步、添加扩展

这时候,一切顺利的话,该扩展已经在modules/scutephp.so这个位置了。下面就是将这个扩展加入到PHP中去,让我们PHP程序可以调用到。
cp modules/scutephp.so /usr/local/php/ext/<br />vim /usr/local/php/etc/php.ini<br />extension=/usr/local/php/ext/scutephp.so #在php.ini文件最后增加这一行<br />service php-fpm restart #重启PHP服务<br />cp ccvita.php /data/www/wwwroot/default/

接下来就可以访问scutephp.php这个文件,测试扩展了。


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn