我将描述如何通过五个步骤构建“Hello World”PHP扩展。
基于 Debian 的操作系统是必需的,因为我们需要使用 apt-get 获取一些工具和依赖项。步骤 1 - 设置构建环境/要求PHP 扩展是编译的 C 代码。我们需要一个 shell(应该已经安装)、一个编辑器(你的选择)、一个编译器(这里我们将使用 GCC)、PHP 本身和 PHP 开发依赖项。sudo apt-get install build-essential php7.0 php7.0-dev
步骤 2 - 配置我们需要在基本配置文件中描述我们的扩展和形成它的文件:文件:config.m4PHP_ARG_ENABLE(php_helloworld, Whether to enable the HelloWorldPHP extension, [ --enable-helloworld-php Enable HelloWorldPHP])
if test "$PHP_HELLOWORLD" != "no"; then
PHP_NEW_EXTENSION(php_helloworld, php_helloworld.c, $ext_shared)
fi如您所见,该NEW_EXTENSION包含一个 C 文件:。php_helloworld.c第 3 步 - 代码让我们为扩展创建 C 代码。首先,我们创建一个头文件:php_helloworld.hPHP_ARG_ENABLE(php_helloworld, Whether to enable the HelloWorldPHP extension, [ --enable-helloworld-php Enable HelloWorldPHP])
if test "$PHP_HELLOWORLD" != "no"; then
PHP_NEW_EXTENSION(php_helloworld, php_helloworld.c, $ext_shared)
fi其次,我们创建源文件:php_helloworld.c// include the PHP API itself
#include <php.h>
// then include the header of your extension
#include "php_helloworld.h"
// register our function to the PHP API
// so that PHP knows, which functions are in this module
zend_function_entry helloworld_php_functions[] = {
PHP_FE(helloworld_php, NULL)
{NULL, NULL, NULL}
};
// some pieces of information about our module
zend_module_entry helloworld_php_module_entry = {
STANDARD_MODULE_HEADER,
PHP_HELLOWORLD_EXTNAME,
helloworld_php_functions,
NULL,
NULL,
NULL,
NULL,
NULL,
PHP_HELLOWORLD_VERSION,
STANDARD_MODULE_PROPERTIES
};
// use a macro to output additional C code, to make ext dynamically loadable
ZEND_GET_MODULE(helloworld_php)
// Finally, we implement our "Hello World" function
// this function will be made available to PHP
// and prints to PHP stdout using printf
PHP_FUNCTION(helloworld_php) {
php_printf("Hello World! (from our extension)\n");
}步骤 4 - 构建现在,我们已准备好构建扩展。首先,我们为 PHP 扩展准备构建环境:phpize
然后我们配置构建并启用我们的扩展:./configure --enable-php-helloworld
最后,我们可以构建它:makesudo make install
步骤 5 - 测试为了测试我们的 PHP 扩展,让我们加载扩展文件并执行我们的函数:helloworld_php.sohelloworld_php()php -d extension=php_helloworld.so -r 'helloworld_php();'网友回复


