探讨:如何编写PHP扩展_php技巧

WBOY
Freigeben: 2016-05-17 09:01:48
Original
909 Leute haben es durchsucht

用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文件:

myext();

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



Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!