首页>新闻动态>尚途学院

教你如何自学PHP扩展

来源:https://www.icvio.com/ 作者:admin 浏览次数:2106次 发布时间:2016-03-04 09:55:39 收藏:添加收藏


本文以PHP7作为语言拓展基础,讲解教你如何从零开始创建一个PHP扩展。该篇主要讲解创建一个扩展的基本步骤。示例中,我们将实现如下功能:


    <?php
        echo sayWord();
    ?>


我们让上面的程序执行结果为:


    $ php ./test.php
    $ hello word


意思为在拓展中实现一个sayWord方法,调用该sayWord方法后,程序将输出:hello word。下面,我将教大家该方法的实现步奏。

从零开始创建一个php扩展



第一步,生成代码


这里php为我们提供了非常棒的生成基本代码的工具ext_skel。该工具在php源代码的./ext目录里面。


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


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


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


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

    $ cd ./sayWord
    $ vim ./config.m4


打开,config.m4文件后,你会发现这样一段文字。


    dnl If your extension references something external, use with:
    dnl PHP_ARG_WITH(sayWord, for say support,
    dnl Make sure that the comment is aligned:
    dnl [  --with-sayWord
    Include sayWord support])
    dnl Otherwise use enable:
    dnl PHP_ARG_ENABLE(sayWord, whether to enable say support,
    dnl Make sure that the comment is aligned:
    dnl [  --enable-sayWord
    Enable sayWord 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(sayWord, for sayWord support,
    dnl Make sure that the comment is aligned:
    dnl [  --with-sayWord      
        Include sayWord support])
    dnl Otherwise use enable:
    PHP_ARG_ENABLE(sayWord, whether to enable sayWord support,
    Make sure that the comment is aligned:
    [  --enable-sayWord
    Enable sayWord support])


第三步,代码实现


修改sayWord.c文件。实现sayWord方法。

找到PHP_FUNCTION(confirm_sayWord_compiled),在其上面增加如下代码:


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


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


    PHP_FE(sayWord, NULL)


修改后的代码如下:


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


第四步,编译安装


编译扩展的步骤如下:


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


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


    [sayWord]
    extension = sayWord.so


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


第五步,调用测试


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



网站建设首选石家庄尚途网络科技有限公司,更多网站优化,网站建设信息请关注:尚途科技,网址:http://www.icvio.com