Backend Development 9 min read

phpy – A PHP Extension for Seamless Integration with the Python Ecosystem

The article introduces phpy, an open‑source Swoole project that embeds the Python ecosystem into PHP, explains its features, provides detailed compilation and installation steps, demonstrates usage through code examples—including AI libraries, GUI creation, named arguments, and callbacks—and shares real‑world sample applications.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
phpy – A PHP Extension for Seamless Integration with the Python Ecosystem

phpy is an open‑source project from the Swoole team that embeds the Python ecosystem into PHP, enabling PHP code to call any Python package and filling gaps in the PHP ecosystem.

It supports popular AI libraries such as PyTorch , transformers , TensorFlow , as well as scientific‑computing packages like NumPy , Pandas , Scikit‑learn , and GUI toolkits PyQt and wxPython .

Source code is hosted on GitHub ( https://github.com/swoole/phpy ) and Gitee ( https://gitee.com/swoole/phpy ).

To compile, you need Python ≥ 3.10 (conda is recommended) and PHP ≥ 8.1. After installing Python under /opt/anaconda3 and ensuring libphp.so and libpython3.11.so are discoverable via /etc/ld.so.conf.d/conda.conf , run sudo ldconfig to refresh the linker cache.

<code>sudo ldconfig -p | grep php
    libphp.so (libc6,x86-64) => /opt/php-8.0/lib/libphp.so
sudo ldconfig -p | grep python
    libpython3.11.so => /opt/anaconda3/lib/libpython3.11.so</code>

Build the extension with:

<code>cd phpy
phpize
./configure
make install</code>

After installation, add extension=phpy.so to php.ini and verify with php -m and php --ri phpy .

When used as a PHP extension, you can import Python modules via PyCore::import('module') , call functions, read attributes, and modify the Python path. Built‑in helper methods include PyCore::str() , PyCore::repr() , PyCore::type() , PyCore::len() , etc.

Core classes such as PyObject , PyDict , PyList , PyTuple , PyStr , and PyModule mirror Python types and inherit from PyObject :

<code>PyObject -> PyModule
         -> PySequence -> PyList
                        -> PyTuple
         -> PySet
         -> PyStr
         -> PyDict
         -> PyType</code>

Integers can be created with PyCore::int() from integers, strings, or floats, and support arithmetic via magic methods like __add__ and __pow__ :

<code>$i = PyCore::int(12345435);
var_dump(strval($i->__pow__(3)));
var_dump(strval($i->__add__(4)));
// Output: 1881564851360655187875 (converted to string because it exceeds 64‑bit range)</code>

Named arguments are supported; positional arguments must precede named ones:

<code>kwargs($a, $b, $c, name: 'hello', world: 'rango');
// Corresponding Python call: kwargs(a, b, c, name='hello', world='rango')</code>

PHP callables can be passed to Python as callbacks by wrapping them with PyCore::fn() :

<code>$m = PyCore::import('app.user');
$uuid = uniqid();
$rs = $m->test_callback(PyCore::fn(function ($namespace) use ($uuid) {
    var_dump($namespace);
    return $uuid;
}));</code>

Real‑world examples include a Tkinter GUI built from PHP and a sentiment‑analysis pipeline using the transformers library:

<code>$tkinter = PyCore::import('tkinter');
$root = $tkinter->Tk();
$root->title('My Window');
$button = $tkinter->Button($root, text: 'Click Me!!', command: PyCore::fn(function () {
    echo 'click me!!' . PHP_EOL;
}));
$button->pack();
$tkinter->mainloop();

$transformers = PyCore::import('transformers');
$sentiment = $transformers->pipeline(model: "lxyuan/distilbert-base-multilingual-cased-sentiments-student", top_k: null);
$rs = $sentiment("I love this movie and i would watch it again and again!");
var_dump(PyCore::scalar($rs));</code>

The article also contains a QR code for a free Python course, but the technical content above provides a complete guide for developers who want to integrate Python functionality into PHP applications.

backendintegrationPythonAIPHPextensionInstallation
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

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