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".

21CTO
21CTO
21CTO
Build a PHP Extension from Scratch with PHP7: A Step‑by‑Step Guide

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=say

The --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 install

Add the extension to php.ini:

[say]
extension = say.so

After 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".

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendTutorialPHP extensionsay-function
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.