The 2020 release of PHP 7.4 has given developers the ability to do something they have never done before – access data structures and call functions written in another language with pure PHP code, no extensions and no bindings to external libraries needed. How is this possible? With PHP FFI (Foreign Function Interface).
In this article, we’re going to discuss what PHP FFI is, its benefits and capabilities, and compare how PHP can work with languages such as Go, Rust, and C++ without the need to create plug-ins. We will also share experiments we used in implementing this function and highlight where we found it most useful and where, in our opinion, it was not worth the trouble.
What is PHP FFI?
In general terms, FFI is an interface that enables developers to use one language to call a library function written in another language. For example, FFI makes it possible to call a function written in Rust, C++, or Go from pure PHP. In order to connect an interpreted language with a compiled language, the libffi [GitHub] library is used – Wiki.
Since the interpreted languages do not know where to specifically search for the parameters of the called function (i.e., in which registers), nor where to get the results of the function after the call, they rely on Libffi to do that work. So, you need to install this library, as it is part of the system libraries (Linux).
Benefits of PHP FFI
While wholly experimental right now, early testing of PHP FFI reveals a host of benefits that could potentially do away with some cumbersome PHP extensions, and ultimately, usher in an interesting new era of development.
- Save time and energy not having to write PHP-specific extensions/modules just to interface with C programs/libraries
- Execute faster on heavy-computing jobs like image and video processing
- Save money launching instances of PHP on common cloud platforms versus launching expensive VM’s and containers
Due to the high potential for encountering various pitfalls, the PHP FFI approach isn’t yet production-ready, but it is promising. The PHP development community even issued their own warning on PHP.net where they introduce the feature.