I haven't used C since the 1980s and 1990s with my own experimentation. I'd like to be able to pick it up again, but this time by building small things in it and then loading it into PHP on Linux.
Does anyone have a very short tutorial for me to make a foo() function in C as a shared object extension loaded in a php.ini? I assume I'll need to use the GCC, but don't know what else I need on my Ubuntu Linux workstation to get this going, or how to compose the files.
Some of the examples I've seen have shown how to do it in C++ or show it as a static extension that must be compiled into PHP. I don't want that -- I want to do it as a C extension, not C++, and load it via php.ini.
I'm thinking of something where I call foo('hello') and it returns 'world' if it sees the incoming string is 'hello'.
For instance, if this was written in 100% PHP, the function might be:
function foo($s) {
switch ($s)
case 'hello':
return 'world';
break;
default:
return $s;
}
}
extension for this example.
<?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);
}
Building Your Extension $ phpize $ ./configure --enable-hello $ make
After running each of these commands, you should have a hello.so
extension=hello.so to your php.ini to trigger it.
php -r 'echo hello_world();'
you are done .;-)
read more here
for Easy way to just try zephir-lang to build php extension with less knowledge of
namespace Test;
/**
* This is a sample class
*/
class Hello
{
/**
* This is a sample method
*/
public function say()
{
echo "Hello World!";
}
}
compile it with zephir and get test extension
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With