书写技术成长之路

PHP Hello World 扩展

  1. 从git下载php源码 git clone http://git.php.net/repository/php-src.git
  2. cd php-src
  3. 切换到指定版本的PHP分支, 例如 git checkout PHP-7.1
  4. 构建 ./buildconf
  5. 指定配置 ./configure --prefix=/etc/php7 --enable-debug --enable-maintainer-zts
  6. make
  7. make install
  8. 复制php.ini文件 'cp php.ini-development /etc/php55/lib/php.ini' 到此,PHP已经编译安装好了,下面开始编写扩展

首先生成扩展的基本框架, 进入到php-src的ext目录,执行 ./ext_skel --extname=hello, 如果执行成功会看到一些说明信息。 然后修改hello/config.m4文件,写入自己的函数逻辑

去掉注释PHP_ARG_ENABLE, 结果如下

PHP_ARG_ENABLE(hello, whether to enable hello support,
Make sure that the comment is aligned:
[  --enable-hello           Enable hello support])

然后再注释掉 AC_DEFINE

AC_DEFINE(HAVE_HELLOLIB,1,[ ])

在ext目录下执行phpize会生成一些配置信息,然后指定配置 ./configure --enable-hello

再次修改helo.c文件 vim hello.c, 添加以下代码

/* {{{ proto string hello_world(string arg)
   Say Hello World to everyone */
PHP_FUNCTION(hello_world)
{
    RETURN_STRING("Hello world");
}
/* }}} */

并更新zend_function_entry函数体

const zend_function_entry hello_functions[] = {
    PHP_FE(confirm_hello_compiled,  NULL)       /* For testing, remove later. */
    PHP_FE(hello_world, NULL)
    PHP_FE_END  /* Must be the last line in hello_functions[] */
};

编译 make

运行 php -i | grep hello查看是否有该扩展,也可以直接修改php.ini文件,在最后面加入extension=hello.so并把编译生成的hello.so复制到PHP扩展目录下就好了, cp /php-src/ext/hello/modules/hello.so /etc/php55/lib/php/extensions/no-debug-non-zts-20121212

执行 php -r 'echo hello_world();'就可以看到hello world了。

参考

http://ahungry.com/blog/2016-09-29-Creating-a-php-7-extension.html