How TypePHP Enables Direct Python Interoperability
This article explains how TypePHP provides seamless, in‑process Python interop for PHP developers, covering the motivation, installation of the phpy runtime, syntax for importing and calling Python modules, data conversion rules, operator support, callbacks, exception handling, IDE helpers, code conversion tools, a practical NumPy linear‑solver example, and known limitations.
Why PHP Needs Python
PHP lacks mature libraries for AI and scientific computing, so developers traditionally resort to separate Python services, RPC, or re‑implement algorithms in PHP, all of which add overhead. TypePHP’s Python interop lets PHP code import and call Python modules directly in the same process, eliminating subprocesses, JSON serialization, and RPC costs.
TypePHP’s Python Runtime (phpy)
TypePHP builds on the phpy extension, which exposes CPython APIs to PHP. TypePHP adds three key capabilities:
Bypassing the Zend VM and calling phpy ’s native C API ( PyCore, PyObject, PyList, etc.) directly.
Compiling PHP code to native machine code, so loops and calculations run faster than interpreted PHP or Python.
Providing a natural, language‑level syntax for Python imports and calls.
Environment Preparation
Python 3.10+ and PHP 8.1+ are required. Install phpy from source, enable it in php.ini, and ensure the same Python interpreter is used for both phpy and any third‑party packages (e.g., numpy).
git clone https://github.com/swoole/phpy.git
cd phpy
phpize
./configure --enable-phpy --with-python-config=/usr/bin/python3-config
make -j
sudo make installImporting Python Modules
Use the use python\module statement to create compile‑time aliases, mirroring PHP namespaces. Modules are lazily loaded on first use, so unused imports cause no errors.
use python\os;
use Python\math;Access module variables as namespace constants ( math\pi) and call functions with namespace function syntax ( math\sqrt(81)). The result is a PyObject that can be printed directly (which invokes toString()) or explicitly converted.
Python Objects in TypePHP
Returned Python objects are wrapped as PyObject. To obtain a native PHP value, call toValue() (which yields int, float, bool, string, or array) or toArray() for deep‑copied PHP arrays. The three conversion methods are: toString() – Python’s string representation. toValue() – explicit conversion to a PHP scalar or array. toArray() – recursive deep copy of Python containers into PHP arrays.
Operators
If either operand is a PyObject, TypePHP forwards the operation to Python’s full operator protocol, supporting arithmetic, bitwise, comparison, identity ( ===), and in‑place operators. Example:
$seven = python\int(7);
$three = python\int(3);
$sum = $seven + $three; // 10
$product = $seven * 10; // 70
$quotient = $seven / 2; // 3.5 (true division)Note that / is true division; floor division must be called via the Python function.
Callbacks
PHP callables (functions, closures, objects) can be passed to Python as synchronous callbacks. Parameters are bound by name, enabling patterns like map:
function main(): void {
$values = python\list([1,2,3]);
$mapped = python\map(fn(int $v): int => $v*2, $values);
$sum = python\sum($mapped)->toValue()->toInt();
echo $sum, "
"; // 12
}Exception Handling
All Python errors are mapped to a PyError exception (subclass of PHP Exception) with properties type, value, error, and traceback. Example:
try {
python\len(); // missing argument
} catch (PyError $e) {
echo "message: ", $e->getMessage(), "
";
echo "type: ", $e->type->__name__, "
";
}Mixing with phpy Native API
You can still use raw phpy classes ( PyCore::import(), new PyList()) alongside the syntactic sugar.
IDE Helper Generation
The tpc --gen-python-helper command creates PHP stub files that give IDEs proper signatures for Python modules (e.g., ide-helper/python/math.php).
Python‑to‑PHP Code Conversion
The tpc --convert-python-to-php tool translates a Python script into a TypePHP program using the namespace syntax, preserving semantics where possible and aborting on unsupported constructs.
Practical Example: Solving a Linear System with NumPy
use python
umpy\linalg as linalg;
use Python
umpy as np;
function main(): void {
$A = np\array([[3,1],[1,2]]);
$b = np\array([9,8]);
$x = linalg\solve($A, $b);
echo 'Solution x: ', $x, "
"; // [2. 3.]
}Running the compiled program prints the solution without any subprocess or RPC.
Limitations
No support for threading, asyncio, or CPython sub‑interpreters.
Cannot compile Python code; modules are loaded by CPython at runtime.
Wildcard imports ( from pkg import *) and built‑in callable syntax are unsupported.
Not suitable for TypePHP WASM targets.
Conclusion
TypePHP’s Python interop fills the biggest gap in the PHP ecosystem—access to AI and scientific‑computing libraries—by allowing direct, high‑performance calls to Python code from compiled PHP. The article walks through setup, syntax, data conversion, operator usage, callbacks, error handling, tooling, a NumPy linear‑solver demo, and current boundaries, enabling developers to integrate Python capabilities into production PHP applications without the overhead of external services.
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.
