如何在Linux GCC上用C构建我的第一个PHP扩展?

Vol*_*ike 20 php c linux

自20世纪80年代和90年代以来,我没有用自己的实验来使用C. 我希望能够再次拿起它,但这一次是在其中构建小东西,然后在Linux上将其加载到PHP中.

有没有人有一个非常简短的教程让我在C中创建一个foo()函数作为php.ini中加载的共享对象扩展?我假设我需要使用GCC,但不知道我在Ubuntu Linux工作站上还需要什么来实现这一目标,或者如何编写文件.

我见过的一些例子已经展示了如何在C++中实现它,或者将它显示为必须编译为PHP的静态扩展.我不希望这样 - 我想将它作为C扩展,而不是C++,并通过php.ini加载它.

我正在考虑我称之为foo('hello')的东西,如果它看到传入的字符串是'hello',它会返回'world'.

例如,如果这是用100%PHP编写的,那么函数可能是:

function foo($s) {
  switch ($s)
    case 'hello':
      return 'world';
      break;
    default:
      return $s;
  }
}
Run Code Online (Sandbox Code Playgroud)

Sau*_*tel 11

此示例的扩展名.

<?php
    function hello_world() {
        return 'Hello World';
    }
?>
Run Code Online (Sandbox Code Playgroud) ### config.m4
PHP_ARG_ENABLE(hello, whether to enable Hello
World support,
[ --enable-hello   Enable Hello World support])
if test "$PHP_HELLO" = "yes"; then
  AC_DEFINE(HAVE_HELLO, 1, [Whether you have Hello World])
  PHP_NEW_EXTENSION(hello, hello.c, $ext_shared)
fi
Run Code Online (Sandbox Code Playgroud) ### php_hello.h
#ifndef PHP_HELLO_H
#define PHP_HELLO_H 1
#define PHP_HELLO_WORLD_VERSION "1.0"
#define PHP_HELLO_WORLD_EXTNAME "hello"

PHP_FUNCTION(hello_world);

extern zend_module_entry hello_module_entry;
#define phpext_hello_ptr &hello_module_entry

#endif
Run Code Online (Sandbox Code Playgroud) #### 你好ç
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_hello.h"

static function_entry hello_functions[] = {
    PHP_FE(hello_world, NULL)
    {NULL, NULL, NULL}
};

zend_module_entry hello_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
    STANDARD_MODULE_HEADER,
#endif
    PHP_HELLO_WORLD_EXTNAME,
    hello_functions,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
#if ZEND_MODULE_API_NO >= 20010901
    PHP_HELLO_WORLD_VERSION,
#endif
    STANDARD_MODULE_PROPERTIES
};

#ifdef COMPILE_DL_HELLO
ZEND_GET_MODULE(hello)
#endif

PHP_FUNCTION(hello_world)
{
    RETURN_STRING("Hello World", 1);
}
Run Code Online (Sandbox Code Playgroud)

构建你的扩展 $ phpize $ ./configure --enable-hello $ make

运行这些命令之后,你应该有一个hello.so

extension = hello.so到你的php.ini来触发它.

 php -r 'echo hello_world();'
Run Code Online (Sandbox Code Playgroud)

你完成了.;-)

在这里阅读更多

轻松的方法只是尝试使用zephir-lang来构建具有较少知识的php扩展

namespace Test;

/**
 * This is a sample class
 */
class Hello
{
    /**
     * This is a sample method
     */
    public function say()
    {
        echo "Hello World!";
    }
}
Run Code Online (Sandbox Code Playgroud)

用zephir编译它并获得测试扩展