This article is based on
PHP7.4 and explains how to create a
PHP extension from scratch. This article will explain the basic steps to create an extension. In the example, we will implement the following functionality.
hello method in the extension to output
hello word! after calling the
Generating the extension archetype
First we need to have a copy of
You can see that there is an
This file is already distributed with
php, so we can customize it very easily.
hello directory is created in the
Extended Archetype Description
config.m4 configuration file
config.m4file tells the
UNIXbuild system which extension
configureoptions are supported, which extension libraries you need, and which source files to compile as part of it. For all frequently used
The purpose of
config.m4is to generate
configurefiles in conjunction with the
configurefile is used for environment testing. It checks if the environment required for the extension to compile and run is met. Now let’s start modifying the
dnlis a comment symbol.
The above code says that if you write an extension that depends on other extensions or
liblibraries, you need to uncomment the
PHP_ARG_WITHrelated code. Otherwise, remove the comments from the
PHP_ARG_ENABLErelated code snippet. We write extensions that do not depend on other extensions and
liblibraries. Therefore, we remove the comment before
The above image is generated with the specification that it does not depend on other extensions.
php_hello.h header file Similar to the C header file, it contains some custom structures and function declarations, which need not be changed in this
hello.c code file
The real logic code is in this file.
Write the code
hello.c is all logic code inside, so we just add code to operate in this file.
Understanding the extension entry
The entry point for the entire extension is the
zend_module_entry structure, the specific definition can be seen in the
zend_modules.h file in the
Zend directory, there are a dozen attributes, quick skip, we only need
hello for now.
Extension-related properties description:
- STANDARD_MODULE_HEADER helps us to implement the first 6 properties
- hello is the name of the extension
- hello_functions is the set of all methods contained in the extension, followed by 5 macros for each of the 5 extension-specific methods
- PHP_HELLO_VERSION is the version number of the extension, defined in the header file, so if you need to change it, just open
- STANDARD_MODULE_PROPERTIES does the rest of the properties for us
hello_functions method array there are already 2 example methods
hello_test2, we refer to them to write our methods, first we write a test method and put it after the function
Then add our newly written functions to the
Compile and install
Since I have a new standalone installation of
php7.4, I’m basically operating with absolute paths. If you have one environment, then just do it directly.
Once installed, let’s configure the extension.