How to Install Zephir and Build Your First PHP Extension
This step‑by‑step guide shows how to install Zephir, set up its parser, configure the environment, create a simple extension skeleton, add a class, compile the extension, and verify it works within PHP.
Zephir Overview
Zephir is an open‑source high‑level language that generates native PHP extensions. It provides strong typing and memory‑safety while allowing developers to write extension code in a syntax similar to PHP.
Installation
Install re2c
sudo apt install re2c re2c --versionBuild and install the Zephir parser extension
git clone git://github.com/zephir-lang/php-zephir-parser.git
cd php-zephir-parser
/usr/local/php-7.4/bin/phpize
./configure --with-php-config=/usr/local/php-7.4/bin/php-config
make -j4
sudo make install # Add to php.ini
[Zephir Parser]
extension=zephir_parser.so php -m | grep zephir_parserInstall Zephir CLI
composer require phalcon/zephir # Add Composer bin directory to PATH (adjust path as needed)
export PATH=$PATH:/home/www/build/tinywan-zephir/vendor/bin
source /etc/profileVerify the CLI is available: <code>zephir help</code>
Creating a Zephir Extension
Check Zephir installation
zephir helpThe command prints the version and a list of available sub‑commands.
Generate an extension skeleton
zephir init utilsThis creates a directory utils with the following layout:
utils/
├── config.json
├── ext/ # generated C source for the extension
└── utils/ # place Zephir source files hereAdd a Zephir class
Create utils/utils/greeting.zep:
namespace Utils;
class Greeting {
public static function say() {
echo "hello world!";
}
public static function tinywan() {
echo "开源技术小栈!";
}
}Build the extension
cd utils
zephir buildOn success the compiled shared object utils.so is placed in the ext/ directory.
Load the extension
# Add to php.ini (global load)
extension=utils.soAlternatively, load for a single CLI invocation with php -d extension=utils.so script.php .
Test the extension
php -m | grep utils # should list the extensionCreate demo01.php:
<?php
declare(strict_types=1);
echo Utils\Greeting::say(), "
";
echo Utils\Greeting::tinywan(), "
"; php demo01.php
hello world!
开源技术小栈!If the output matches, the Zephir‑based PHP extension is correctly built and loaded.
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.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
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.
