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

cd phpy
phpize
./configure
make install

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

cmake .
make -j

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

Usage

Importing Modules

$os = PyCore::import('os');

Calling Functions and Accessing Attributes

$uname = $os->uname();
echo $uname->sysname;

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:

$i1 = PyCore::int(12345678);
$i2 = PyCore::int('1234567890123456789012345678901234567890');
$i3 = PyCore::int(12345678.03);

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

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

Named Parameters

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

kwargs($a, $b, $c, name: 'hello', world: 'rango');

Callback Functions

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

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

Practical Examples

Tkinter GUI from PHP

<?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();
?>

Sentiment Analysis with Transformers

<?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));
?>

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPythonExtensionInterop
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

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.