Backend Development 10 min read

phpy – A PHP Extension for Seamless Python Integration

phpy is an open‑source Swoole project that lets PHP import and use Python packages—including popular AI and scientific libraries—by providing a PHP extension or a Python C module, with detailed installation steps, usage examples, and support for callbacks and named parameters.

php中文网 Courses
php中文网 Courses
php中文网 Courses
phpy – A PHP Extension for Seamless Python Integration

phpy is the latest open‑source project from the Swoole team, designed to bring the Python ecosystem into PHP by allowing PHP code to import and call any Python package, thereby filling gaps in the PHP ecosystem.

It supports widely used AI libraries such as PyTorch , transformers , TensorFlow , as well as scientific packages like Numpy , Pandas , Scikit , and GUI toolkits such as PyQt and wxPython .

It is not recommended to use phpy in short‑lived environments such as php‑fpm/apache because frequent module import/destruction can consume significant resources.

Compilation and Installation

phpy can be built either as a PHP extension or as a Python C module, enabling bidirectional calls between PHP and Python.

Dependencies

Python 3.10 or higher (conda is recommended for installation).

PHP 8.1 or higher.

Python is typically installed under /opt/anaconda3 , with its binaries, headers, and libraries located in the standard sub‑directories. The system library configuration must include both /opt/anaconda3/lib and /opt/php-8.1/lib , after which ldconfig should be run to locate libpython3.11.so and libphp.so .

Installing as a PHP Extension

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

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

Installing as a Python Module

<code>cmake .
make -j</code>

The build produces tests/lib/phpy.so , which can be imported directly in Python using import phpy .

Usage

Importing Modules

<code>$os = PyCore::import('os');</code>

Calling Functions and Accessing Attributes

<code>$uname = $os->uname();
echo $uname->sysname;</code>

Modifying Load Paths

Use PyCore::import('sys')->path->append('/workspace') to add custom directories to sys.path , then import packages such as app.user .

Built‑in Methods

PyCore::str() – convert an object to string

PyCore::repr()

PyCore::type() – get object type

PyCore::locals() – current local variables

PyCore::globals() – global variables

PyCore::hash() – hash value

PyCore::hasattr() – attribute existence check

PyCore::id() – internal identifier

PyCore::len() – length

PyCore::dir() – list attributes and methods

PyCore::int() – construct integer

PyCore::float() – construct float

PyCore::fn() – wrap a callable as a Python function

PyCore::scalar() – convert a PyObject to a PHP scalar

Built‑in Classes

PyObject – base class for all other types

PyDict – dictionary, maps to PHP associative array

PyList – list, maps to PHP indexed array

PyTuple – immutable list

PyStr – string

PyModule – Python package, subclass of PyObject

Integer Handling

Python’s unlimited‑precision integers can be used via PyCore::int() . Example:

<code>$i1 = PyCore::int(12345678);
$i2 = PyCore::int('1234567890123456789012345678901234567890');
$i3 = PyCore::int(12345678.03);</code>

Operations such as power and addition are performed through magic methods:

<code>$i = PyCore::int(12345435);
var_dump(strval($i->__pow__(3)));
var_dump(strval($i->__add__(4)));
</code>

Named Parameters

phpy supports named parameters; positional arguments must precede named ones.

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

Callback Functions

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>

Practical Examples

Tkinter GUI from PHP

<code>&lt;?php
$tkinter = PyCore::import('tkinter');
$root = $tkinter->Tk();
$root->title('我的窗口');
$root->geometry('500x500');
$root->resizable(False, False);
$button = $tkinter->Button($root, text: 'Click Me!!', command: PyCore::fn(function () {
    var_dump(func_get_args());
    echo 'click me!!' . PHP_EOL;
}));
$button->pack();
$tkinter->mainloop();
?>
</code>

Sentiment Analysis with Transformers

<code>&lt;?php
$transformers = PyCore::import('transformers');
$os = PyCore::import('os');
$os->environ->__setitem__('https_proxy', getenv('https_proxy'));
$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>

These examples demonstrate how phpy enables PHP developers to leverage Python’s rich ecosystem—including AI, scientific computing, and GUI libraries—directly from PHP code.

backendPythonAIextensioninterop
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

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.