探讨:如何编写PHP扩展

用C/C++扩展php的优缺点:
优点:
效率,还是效率
减少php脚本的复杂度, 极端情况下, 你只需要在php脚本中,简单的调用一个扩展实现的函数,然后你所有的功能都就被扩展实现了
而缺点也是显而易见的:
开发复杂
可维护性降低
开发周期变长, 最简单的一个例子,当你用php脚本的时候, 如果你发现某个判断条件出错,你只要修改了这一行,保存,那么就立刻能见效。 而如果是在C/C++编写的php扩展中, 那你可需要,修改源码,重新编译,然后重新load进php, 然后重启Apache,才能见效。
如果你熟悉C,那么编写一个php扩展,并不是什么非常难的事情。 php本身就提供了一个框架,来简化你的开发。
最简单的方式来开始一个php扩展的开发,是使用php提供的扩展框架wizard ext_skel, 它会生成一个php扩展所必须的最基本的代码, 要使用它,首先你要下载php的源码,或者开发包, 进入php源码的ext目录, 就会发现这个工具。
生成一个扩展:
./ext_skel --extname=myext
进入/myext,选择扩展类型:
vi config.m4
下面两种类型选一个就行了:
复制代码 代码如下:
//(依赖外部库)
dnl php_ARG_WITH(myext, for myext support,
dnl Make sure that the comment is aligned:
dnl [ --with-myext Include myext support])
//去掉dnl
 php_ARG_WITH(myext, for myext support,
 Make sure that the comment is aligned:
 [  --with-myext             Include myext support])

//或者将 //(不依赖外部库) dnl php_ARG_ENABLE(myext, whether to enable myext support,dnl Make sure that the comment is aligned:dnl [ --enable-myext Enable myext support])//去掉dnl
修改头文件php_myext.h:
//php_FUNCTION(confirm_myext_compiled); /* For testing, remove later. */
//修改为
php_FUNCTION(myext); /* For testing, remove later. */
修改myext.c:
//将
//zend_function_entry myext_functions[] = {
// php_FE(confirm_myext_compiled, NULL) /* For testing, remove later. */
// {NULL, NULL, NULL} /* Must be the last line in myext_functions[] */
//};
//修改为
zend_function_entry myext_functions[] = {
php_FE(myext, NULL) /* For testing, remove later. */
{NULL, NULL, NULL} /* Must be the last line in myext_functions[] */
};
//在文件底部添加自己的函数
php_FUNCTION(myext)
{
zend_printf("Hello World!/n");
}
安装自己的php扩展myext:
/usr/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config
make
make install


修改php.ini,添加:
extension = "myext.so"
重启web服务器,查看phpinfo,即可看到自己的扩展:



新建测试php文件:

<?php
myext();

执行此文件,即可看到再熟悉不过的“Hello World!”。



php技术探讨:如何编写PHP扩展,转载需保留来源!

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。