Build a PHP Extension from Scratch with PHP7: A Step‑by‑Step Guide
This tutorial walks you through creating a PHP7 extension from the ground up, covering code generation, config adjustments, function implementation, compilation, installation, and testing of a simple 'say' method that outputs "hello word".
This article uses PHP7 as a base to explain how to create a PHP extension from zero, implementing a say function that prints "hello word".
Step 1: Generate the Extension Skeleton
PHP provides the ext_skel tool in the ./ext directory of the source tree to generate basic extension code.
$ cd php_src/ext/
$ ./ext_skel --extname=sayThe --extname value becomes the extension name, and a directory named say is created.
Step 2: Edit config.m4
The config.m4 file works with phpize to produce a configure script that checks the build environment. Open the file and adjust the comments:
dnl If your extension references something external, use with:
dnl PHP_ARG_WITH(say, for say support,
dnl [ --with-say Include say support])
dnl Otherwise use enable:
dnl PHP_ARG_ENABLE(say, whether to enable say support,
dnl [ --enable-say Enable say support])Since this extension has no external dependencies, remove the comment marker before the PHP_ARG_ENABLE block.
Step 3: Implement the Extension Code
Modify say.c to add the say function:
PHP_FUNCTION(say)
{
zend_string *strg;
strg = strpprintf(0, "hello word");
RETURN_STR(strg);
}Register the function in the function entry list:
PHP_FE(say, NULL) /* For testing, remove later. */
PHP_FE(confirm_say_compiled, NULL) /* For testing, remove later. */
PHP_FE_END /* Must be the last line in say_functions[] */Step 4: Compile and Install
Run the standard build steps:
$ phpize
$ ./configure
$ make && make installAdd the extension to php.ini:
[say]
extension = say.soAfter installation, verify the extension is loaded with php -m, which should list say.
Step 5: Test the Extension
Create a PHP script that calls say() and confirm the output matches the expected "hello word".
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
