用C/C++擴(kuò)展PHP的優(yōu)缺點(diǎn):
優(yōu)點(diǎn):
效率,還是效率
減少PHP腳本的復(fù)雜度, 極端情況下, 你只需要在PHP腳本中,簡單的調(diào)用一個(gè)擴(kuò)展實(shí)現(xiàn)的函數(shù),然后你所有的功能都就被擴(kuò)展實(shí)現(xiàn)了
而缺點(diǎn)也是顯而易見的:
開發(fā)復(fù)雜
可維護(hù)性降低
開發(fā)周期變長, 最簡單的一個(gè)例子,當(dāng)你用PHP腳本的時(shí)候, 如果你發(fā)現(xiàn)某個(gè)判斷條件出錯(cuò),你只要修改了這一行,保存,那么就立刻能見效。 而如果是在C/C++編寫的PHP擴(kuò)展中, 那你可需要,修改源碼,重新編譯,然后重新load進(jìn)PHP, 然后重啟Apache,才能見效。
如果你熟悉C,那么編寫一個(gè)PHP擴(kuò)展,并不是什么非常難的事情。 PHP本身就提供了一個(gè)框架,來簡化你的開發(fā)。
最簡單的方式來開始一個(gè)PHP擴(kuò)展的開發(fā),是使用PHP提供的擴(kuò)展框架wizard ext_skel, 它會(huì)生成一個(gè)PHP擴(kuò)展所必須的最基本的代碼, 要使用它,首先你要下載PHP的源碼,或者開發(fā)包, 進(jìn)入PHP源碼的ext目錄, 就會(huì)發(fā)現(xiàn)這個(gè)工具。
生成一個(gè)擴(kuò)展:
./ext_skel --extname=myext
進(jìn)入/myext,選擇擴(kuò)展類型:
vi config.m4
下面兩種類型選一個(gè)就行了:
復(fù)制代碼 代碼如下:
//(依賴外部庫)
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-myextInclude 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[] */
};
//在文件底部添加自己的函數(shù)
PHP_FUNCTION(myext)
{
zend_printf("Hello World!/n");
}
安裝自己的php擴(kuò)展myext:
/usr/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config
make
make install
新建測試php文件:
<?php
myext();
執(zhí)行此文件,即可看到再熟悉不過的“Hello World!”。
新聞熱點(diǎn)
疑難解答