2009-08-09 74 views
18

自20世纪80年代和90年代以来,我没有使用C语言进行自己的实验。我希望能够再次拿起它,但是这次通过在它上面创建小的东西,然后将它加载到Linux上的PHP中。如何在Linux GCC的C语言中构建我的第一个PHP扩展?

有没有人有一个非常简短的教程,让我在C中作为一个共享对象扩展在php.ini中加载一个foo()函数?我假设我需要使用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; 
    } 
} 

回答

6

扩展这个例子。

<?php 
    function hello_world() { 
     return 'Hello World'; 
    } 
?> 
###的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 
### 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 
#### hello.c的
#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); 
} 

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

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

延长= hello.so到php.ini来触发它。

php -r 'echo hello_world();' 

你做。;-)

为简单的方法来只是尝试ZEPHIR琅构建PHP扩展与

namespace Test; 

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

编译的知识较少读更多here

它与zephir和获得测试扩展

+0

请提供文档网址。 – 2017-04-14 19:26:00

+0

已经提供 – 2017-04-15 04:56:38

2

试图Saurabh的实例用PHP 7.1.6 mple,发现需要进行一些小的改动:

  • 变化function_entryzend_function_entry
  • 更换RETURN_STRING("Hello World", 1)RETURN_STRING("Hello World")

这是一个很好的例子代码开始PHP扩展开发!谢谢!