PHPackages                             swoole/phpx - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. swoole/phpx

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

swoole/phpx
===========

C++ wrapper for Zend API

v2.5.0(1w ago)8622111031Apache-2.0C++CI failing

Since Aug 22Pushed 1w ago71 watchersCompare

[ Source](https://github.com/swoole/phpx)[ Packagist](https://packagist.org/packages/swoole/phpx)[ RSS](/packages/swoole-phpx/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (10)Dependencies (22)Versions (31)Used By (1)

[![Swoole Logo](logo.png)](logo.png)
====================================

[](#)

[![Twitter](https://camo.githubusercontent.com/938a48bafad518c277315ee27ebefa0a0ca9f7cde918eef1820810964ff6e9f5/68747470733a2f2f62616467656e2e6e65742f62616467652f69636f6e2f747769747465723f69636f6e3d74776974746572266c6162656c)](https://twitter.com/phpswoole)[![Discord](https://camo.githubusercontent.com/155081771f1f717ebd6be59f0cb88fb4ac65ee4a70fec13715509f7e280fdd50/68747470733a2f2f62616467656e2e6e65742f62616467652f69636f6e2f646973636f72643f69636f6e3d646973636f7264266c6162656c)](https://discord.swoole.dev)[![Build Status](https://github.com/matyhtf/phpx/workflows/libphpx/badge.svg)](https://github.com/matyhtf/phpx/actions?query=workflow%3Alibphpx)[![License](https://camo.githubusercontent.com/1d48dd9fe6bf24b648040a29de372f089b9340226a4fb00214784dfb402cdda1/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d617061636865322d626c75652e737667)](LICENSE)[![Latest Release](https://camo.githubusercontent.com/22f7562c52a318bba0347108dff68227ee0a71348346275c78ded9dbfa569ad1/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f73776f6f6c652f706870782e737667)](https://github.com/swoole/phpx/releases/)[![Codecov](https://camo.githubusercontent.com/da77b9df00ef9c58e2ca959ac951ffc72dca1a80b76e8e1c238f417bc6505503/68747470733a2f2f636f6465636f762e696f2f67682f73776f6f6c652f706870782f6272616e63682f6d61737465722f67726170682f62616467652e737667)](https://codecov.io/gh/swoole/phpx)

C++ wrapper for Zend API

[简体中文](README-CN.md)

Requirements
------------

[](#requirements)

- PHP 8.2 or later
- Linux/macOS/Windows
- GCC 9 or later (with C++17 support)
- Composer

Installation
------------

[](#installation)

### Build libphpx.so

[](#build-libphpxso)

```
# Standard build (Release mode)
cmake .
make -j 4
sudo make install
sudo ldconfig
```

### Debug Mode (for troubleshooting)

[](#debug-mode-for-troubleshooting)

```
# Clean previous builds
cmake --build . --target clean

# Configure Debug mode (includes debug symbols and runtime checks)
cmake -DCMAKE_BUILD_TYPE=Debug .

# Compile
make -j 4
sudo make install
sudo ldconfig
```

**Debug Mode Features:**

- ✅ Generates complete debug symbols
- ✅ Disables compiler optimizations for easier debugging
- ✅ Enables runtime error checking
- ✅ More detailed compilation output

Quick Start
-----------

[](#quick-start)

### Create a New Extension Project

[](#create-a-new-extension-project)

```
# Create extension project
composer create-project swoole/phpx-ext test
cd test
```

### Basic Usage Example

[](#basic-usage-example)

Here's a complete example demonstrating modern PHPX extension development:

```
#include "phpx_ext.h"

// Include auto-generated arginfo header (generated by gen_stub.php)
BEGIN_EXTERN_C()
#include "your_extension_arginfo.h"
END_EXTERN_C()

using namespace php;
using namespace std;

// Method implementation using PHPX_METHOD macro
PHPX_METHOD(MyClass, __construct) {
    // Initialize object properties
    _this.set("name", args[0].toString());
    _this.set("value", args[1].toInt());
    return nullptr;
}

PHPX_METHOD(MyClass, greet) {
    // Access object properties
    auto name = _this.get("name");
    auto value = _this.get("value");

    // Return formatted string
    return "Hello, " + name.toStdString() + "! Value: " + to_string(value.toInt());
}

PHPX_METHOD(MyClass, processData) {
    // Work with Array type
    Array input = args[0];
    Array result;

    // Iterate and transform
    for (auto &item : input) {
        result.append(item.value.toInt() * 2);
    }

    return result;
}

// Function implementation using PHPX_FUNCTION macro
PHPX_FUNCTION(my_extension_func) {
    // Variant - universal type container
    Variant str_var = "Hello PHPX";
    Variant int_var = 42;
    Variant float_var = 3.14159;

    // Array operations
    Array arr;
    arr.set("name", "PHPX");
    arr.set("version", 8.2);
    arr.set("features", Array{"C++17", "Type-safe", "Modern API"});

    // Object creation and method calls
    Object datetime = newObject("DateTime");
    auto formatted = datetime.call("format", {"Y-m-d H:i:s"});

    // Facade functions - direct PHP function calls
    php::var_dump(arr);                    // Debug output
    php::print_r(datetime);                // Print object

    // File operations
    auto content = php::file_get_contents("/etc/hosts");
    if (content.isString()) {
        echo("File length: ", content.length(), "\n");
    }

    // Array manipulation with references
    Array numbers{1, 2, 3, 4, 5};
    Reference ref = numbers.toReference();
    php::sort(ref);                        // Sort array
    php::array_push(ref, 6, 7, 8);        // Push elements

    RETURN_STRING("PHPX Demo Completed!");
}

// Extension entry point
PHPX_EXTENSION() {
    Extension *ext = new Extension("my_extension", "1.0.0");

    // Register lifecycle callbacks
    ext->onStart = [ext]() noexcept {
        // Register constants
        ext->registerConstant("MY_EXT_VERSION", 10000);

        // Register class with methods
        Class *c = new Class("MyClass");
        c->addProperty("name", "", ZEND_ACC_PUBLIC);
        c->addProperty("value", 0, ZEND_ACC_PUBLIC);
        c->registerFunctions(class_MyClass_methods);  // From arginfo header
        ext->registerClass(c);

        // Register standalone functions
        ext->registerFunction(PHPX_FN(my_extension_func));
    };

    // PHP info page configuration
    ext->info({"my_extension support", "enabled"},
              {
                  {"author", "Your Name"},
                  {"version", ext->version},
                  {"github", "https://github.com/your/repo"},
              });

    return ext;
}
```

**Key Features:**

- **PHPX\_METHOD/PHPX\_FUNCTION**: Modern macros for cleaner code
- **Extension/Class API**: Object-oriented extension registration
- **Lambda callbacks**: Flexible lifecycle management with `onStart`, `onShutdown`, etc.
- **Type-safe wrappers**: `Variant`, `Array`, `Object`, `String` classes
- **Facade functions**: Direct PHP function calls via `php::` namespace
- **Auto-generated arginfo**: Use `gen_stub.php` to generate type information

### Generate ArgInfo &amp; Function Entries

[](#generate-arginfo--function-entries)

```
php vendor/swoole/phpx/bin/gen_stub.php your_stub_dir
```

### Build Your Extension

[](#build-your-extension)

```
cd test
cmake .
make -j 4
make install
```

### Load Your Extension

[](#load-your-extension)

Edit `php.ini` and add:

```
extension=test.so
```

### Test Your Extension

[](#test-your-extension)

Create a test file `test.php`:

```

```

Run it:

```
php test.php
```

Expected output:

```
Hello, World!

```

Advanced Usage
--------------

[](#advanced-usage)

### 1. Variant Type Usage

[](#1-variant-type-usage)

Variant is a universal type container that can hold any PHP value:

```
#include "phpx.h"

using namespace php;

// Create variants of different types
Variant str_var = "Hello PHPX";
Variant int_var = 42;
Variant float_var = 3.14159;
Variant bool_var = true;
Variant null_var;

// Type checking
if (str_var.isString()) {
    echo("String: ", str_var.toCString());
}

if (int_var.isInt()) {
    echo("Integer: ", int_var.toInt());
}

// Type conversion
auto str = int_var.toString();      // Convert to string
auto num = str_var.toInt();         // Convert to integer (0 if not numeric)

// Comparison
if (str_var.equals("Hello PHPX")) {
    echo("Match!");
}

// Serialization
Variant serialized = str_var.serialize();
Variant unserialized = serialized.unserialize();
```

### 2. Array Type Usage

[](#2-array-type-usage)

Array provides a C++ wrapper for PHP arrays with rich functionality:

```
#include "phpx.h"

using namespace php;

// Create arrays
Array arr;
arr.set("name", "PHPX");
arr.set("version", 8.2);
arr.set("features", Array{"C++17", "Type-safe", "Modern API"});

// Initialize with list
Array numbers{1, 2, 3, 4, 5};
Array map{{"key1", "value1"}, {"key2", "value2"}};

// Access elements
auto name = arr.get("name");
auto first = numbers[0];

// Check existence
if (arr.exists("name")) {
    echo("Name exists");
}

// Iterate array
for (auto &item : arr) {
    echo(item.key, ": ", item.value, "\n");
}

// Array operations
arr.append("new_element");          // Add element
arr.del("name");                    // Remove element
auto count = arr.count();           // Get count
auto keys = arr.keys();             // Get all keys

// Nested arrays
Array nested;
nested.set("level1", Array{
    {"level2", Array{"deep_value"}}
});
auto deep = nested.item("level1").item("level2");

// Reference for modification
Array nums{5, 2, 8, 1, 9};
Reference ref = nums.toReference();
php::sort(ref);                     // Sort in place
php::array_push(ref, 10, 11);       // Push elements
```

### 3. Object Type Usage

[](#3-object-type-usage)

Object wraps PHP objects and provides method calling capabilities:

```
#include "phpx.h"

using namespace php;

// Create object
Object datetime = newObject("DateTime");

// Call methods
auto formatted = datetime.call("format", {"Y-m-d H:i:s"});
echo("Current time: ", formatted.toCString());

// Set properties
Object stdclass = newObject("stdClass");
stdclass.set("name", "test");
stdclass.set("value", 42);

// Get properties
auto name = stdclass.get("name");
auto value = stdclass.get("value");

// Check property existence
if (stdclass.exists("name")) {
    echo("Property exists");
}

// Create object with constructor arguments
Object arrayObj = newObject("ArrayObject", {
    Array{1, 2, 3, 4, 5}
});

// Call method and get result
auto count = arrayObj.call("count");
echo("Count: ", count.toInt());

// Static method calls
auto result = Object::callStatic("DateTime", "createFromFormat", {
    "Y-m-d", "2024-01-01"
});
```

### 4. Facade Encapsulation API

[](#4-facade-encapsulation-api)

PHPX provides facade functions in the `php::` namespace for direct PHP function calls:

```
#include "phpx.h"
#include "phpx_func.h"

using namespace php;

// Debug and output
php::var_dump(some_variable);           // Debug output
php::print_r(some_variable);            // Print readable
php::echo("Hello", " ", "World");      // Echo strings

// File operations
auto content = php::file_get_contents("/path/to/file.txt");
php::file_put_contents("/path/to/file.txt", "content");

// Array manipulation (requires reference)
Array arr{5, 2, 8, 1, 9};
Reference ref = arr.toReference();

php::sort(ref);                         // Sort array
php::rsort(ref);                        // Reverse sort
php::shuffle(ref);                      // Shuffle
php::array_push(ref, 10, 11);          // Push elements
php::array_pop(ref);                    // Pop element
php::array_shift(ref);                  // Shift element
php::array_unshift(ref, 0);            // Unshift element

// String operations
auto upper = php::strtoupper("hello");
auto lower = php::strtolower("HELLO");
auto length = php::strlen("hello");
auto pos = php::strpos("hello world", "world");

// Math operations
auto max_val = php::max({1, 2, 3, 4, 5});
auto min_val = php::min({1, 2, 3, 4, 5});
auto sum = php::array_sum(Array{1, 2, 3, 4, 5});
auto rand_val = php::rand(1, 100);

// JSON operations
Array data{{"name", "PHPX"}, {"version", 8.2}};
auto json_str = php::json_encode(data);
auto decoded = php::json_decode(json_str, true);

// Other useful functions
php::sleep(2);                          // Sleep 2 seconds
auto time = php::time();                // Current timestamp
auto date = php::date("Y-m-d H:i:s");  // Formatted date
```

### 5. Built-in Class Facade Encapsulation

[](#5-built-in-class-facade-encapsulation)

PHPX provides facade classes for popular PHP extensions:

```
#include "phpx.h"
#include "phpx_class.h"

using namespace php;

// Redis example
Redis redis{};
redis.connect("127.0.0.1", 6379);

// String operations
redis.set("name", "PHPX");
redis.set("version", "8.2");
auto name = redis.get("name");
echo("Name: ", name.toCString());

// Check existence
if (redis.exists("name")) {
    echo("Key exists");
}

// Multiple operations
redis.mset({
    {"key1", "value1"},
    {"key2", "value2"},
    {"key3", "value3"}
});

auto values = redis.mget({"key1", "key2", "key3"});

// List operations
redis.rpush("mylist", "item1");
redis.rpush("mylist", "item2");
auto list_len = redis.llen("mylist");

// Hash operations
redis.hset("user:1", "name", "John");
redis.hset("user:1", "email", "john@example.com");
auto user_name = redis.hget("user:1", "name");

// Set expiration
redis.expire("name", 3600);  // Expire in 1 hour

// Delete keys
redis.del("key1", "key2");

// Close connection
redis.close();
```

**Note:** To use Redis facade, ensure the Redis extension is loaded in your PHP environment.

Documentation
-------------

[](#documentation)

For more detailed documentation, please check:

- [Architecture Guide](docs/architecture.md)
- [API Reference](docs/api-reference.md)
- [Quick Start Guide](docs/quickstart.md)
- [Testing Guide](docs/testing-guide.md)
- [Debugging Guide](docs/debugging-guide.md)

Examples
--------

[](#examples)

Check out the [examples directory](examples/) for more comprehensive examples including:

- Bloom filter implementation
- Queue data structure
- RocksDB integration
- GTK application
- And more!

Language
--------

[](#language)

- [English](README.md)
- [中文](README-CN.md)

License
-------

[](#license)

PHPX is open-sourced software licensed under the [Apache License 2.0](LICENSE).

###  Health Score

55

—

FairBetter than 97% of packages

Maintenance98

Actively maintained with recent releases

Popularity40

Moderate usage in the ecosystem

Community32

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 96.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~12 days

Recently: every ~2 days

Total

29

Last Release

9d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e1dea9261ba377a13a16e7e0f3883e73bda4094551ddea280e852f23a5d248c0?d=identicon)[Tianfeng.Han](/maintainers/Tianfeng.Han)

---

Top Contributors

[![matyhtf](https://avatars.githubusercontent.com/u/2017766?v=4)](https://github.com/matyhtf "matyhtf (801 commits)")[![owenliang](https://avatars.githubusercontent.com/u/7803472?v=4)](https://github.com/owenliang "owenliang (15 commits)")[![Yurunsoft](https://avatars.githubusercontent.com/u/20104656?v=4)](https://github.com/Yurunsoft "Yurunsoft (4 commits)")[![NathanFreeman](https://avatars.githubusercontent.com/u/33935209?v=4)](https://github.com/NathanFreeman "NathanFreeman (3 commits)")[![limingxinleo](https://avatars.githubusercontent.com/u/16648551?v=4)](https://github.com/limingxinleo "limingxinleo (2 commits)")[![kong36088](https://avatars.githubusercontent.com/u/11497913?v=4)](https://github.com/kong36088 "kong36088 (2 commits)")[![heyanlong](https://avatars.githubusercontent.com/u/3367958?v=4)](https://github.com/heyanlong "heyanlong (1 commits)")[![shiguangqi](https://avatars.githubusercontent.com/u/654869?v=4)](https://github.com/shiguangqi "shiguangqi (1 commits)")[![deminy](https://avatars.githubusercontent.com/u/865547?v=4)](https://github.com/deminy "deminy (1 commits)")

---

Tags

phpextensionembeddedZendAPI

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/swoole-phpx/health.svg)

```
[![Health](https://phpackages.com/badges/swoole-phpx/health.svg)](https://phpackages.com/packages/swoole-phpx)
```

###  Alternatives

[civicrm/civicrm-core

Open source constituent relationship management for non-profits, NGOs and advocacy organizations.

762297.9k53](/packages/civicrm-civicrm-core)[rubix/tensor

A library and extension that provides objects for scientific computing in PHP.

2801.6M5](/packages/rubix-tensor)[memio/spec-gen

phpspec extension for better code generation

66204.9k28](/packages/memio-spec-gen)[phpxmlrpc/polyfill-xmlrpc

A pure-php reimplementation of the API exposed by the native XML-RPC extension

12442.2k3](/packages/phpxmlrpc-polyfill-xmlrpc)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
