自从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;
}
}
发布于 2015-08-18 13:22:28
此示例的扩展。
<?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 $./--enable--hello$
在运行上述每个命令之后,您应该拥有一个hello.so
通过extension=hello.so连接到您的php.ini以触发它。
php -r 'echo hello_world();'
您完成了。;-)
阅读更多here
要简单地尝试zephir-lang来构建php扩展,只需要更少的知识
namespace Test;
/**
* This is a sample class
*/
class Hello
{
/**
* This is a sample method
*/
public function say()
{
echo "Hello World!";
}
}
使用zephir编译并获取测试扩展
发布于 2017-07-22 09:43:52
在PHP 7.1.6中尝试了Saurabh的示例,发现需要进行一些小的更改:
使用RETURN_STRING("Hello World")
将
function_entry
更改为RETURN_STRING("Hello World", 1)
这是一个开始PHP扩展开发的很好的示例代码!谢谢!
https://stackoverflow.com/questions/1250412
复制相似问题