准备环境

  • 本次开发使用ubuntu 14.04

  • php 7.1,从github clone到本地

创建扩展项目

1、进入到php-src目录,cd ext,执行命令.ext_skel --extname=helloworld
输出以下内容:

To use your new extension, you will have to execute the following steps:

  1. $ cd ..

  2. $ vi ext/myext/config.m4

  3. $ ./buildconf

  4. $ ./configure --[with|enable]-myext

  5. $ make

  6. $ ./sapi/cli/php -f ext/myext/myext.php

  7. $ vi ext/myext/myext.c

  8. $ make

Repeat steps 3-6 until you are satisfied with ext/myext/config.m4 and
step 6 confirms that your module is compiled into PHP. Then, start writing
code and repeat the last two steps as often as necessary.

注意,如果使用homestead虚拟机来进行开发,一定要注意文件格式问题。在homestead中执行上述命令可能会出现下面的错误提示:

./ext_skel --extname=<extname>

-bash: ./ext_skel: /bin/sh^M: bad interpreter: No such file or directory

解决方案:用notepad++打开ext_skel文件,打开设置>首选项,按下图更改设置:

\1.PNG

Creating directory myext
Creating basic files: config.m4 config.w32 .gitignore myext.c php_myext.h CREDITS EXPERIMENTAL tests/001.phpt myext.php [done].

2、打开config.m4,将10到12行的代码注释去掉,如下

PHP_ARG_WITH(helloworld, for helloworld support,
dnl Make sure that the comment is aligned:
[  --with-helloworld             Include helloworld support])

3、打开helloworld.c,添加hello world导出函数,同时添加到编译列表里面

PHP_FUNCTION(my_hello_world)
{
    php_printf("zshanjun hell world");
    RETURN_TRUE;
}

const zend_function_entry helloworld_functions[] = {
        PHP_FE(confirm_helloworld_compiled,     NULL) 
        PHP_FE(my_hello_world,              NULL)         
        PHP_FE_END      /* Must be the last line in helloworld_functions[] */
};

4、使用一下命令对helloworld扩展进行编译

phpize  //用来生成配置文件
./configure --with-php-config=php-config 
make
make install

5、设置php.ini文件,添加一行extension=helloworld.so
ps: php.ini位置 /etc/php/7.0/fpm/php.ini
ps: sudo service php7.0-fpm restart重启php-fpm

6、查看成果
在一个php页面中直接调用echo my_hello_world()即可


参考网站:


PHP扩展开发

登陆发表评论