Learning Where to Use FFI

Learn about when FFI was introduced, the reasons to use it, and the reasons not to.

The potential for importing C libraries directly into PHP is truly staggering. One of the PHP core developers actually used the FFI extension to bind PHP to the C-language TensorFlow machine learning platform!

As we show in this section, the FFI extension is not a magic solution for all of our needs. This section discusses the main strengths and weaknesses of the FFI extension, as well as gives us guidelines for its use. A myth we debunk in this section is that making direct C-language calls using the FFI extension speeds up PHP 8 program execution. First, let’s have a look at what took so long to get the FFI extension into PHP.

Adopting FFI into PHP

The first FFI extension was actually introduced for PHP 5 on the PECL website in January 2004 by PHP core developers Wez Furlong and Ilia Alshanetsky. The project never passed its Alpha stage, however, and development was dropped within a month.

As PHP developed and matured over the next 14 years, it became apparent that PHP would benefit from the ability to rapidly prototype potential extensions directly within a PHP script. Without this capability, PHP was in danger of falling behind other languages such as Python and Ruby.

In the past, lacking a fast-prototyping capability, extension developers were forced to compile their full extension and install it using pecl, before being able to test it in a PHP script. In some cases, developers had to recompile PHP itself just to test their new extension! In contrast, the FFI extension allows a developer to directly place C function calls inside the PHP script for immediate testing.

Starting with PHP 7.4 and carried on into PHP 8, an improved version of the FFI extension was proposed by core developer Dmitry Stogov. After a compelling proof of concept (see the preceding Tip box regarding PHP binding to the TensorFlow machine learning platform), this FFI extension version was incorporated into the PHP language.

Let’s now examine why FFI should not be used to gain speed.

Avoid employing FFI for speed gains

Because the FFI extension allows PHP direct access to C-language libraries, there is a temptation to believe that our PHP applications will suddenly operate blindingly fast at machine-language speeds. Unfortunately, this is not the case. The FFI extension needs to first open the given C library and then parse and pseudocompile an FFI instance before execution. The FFI extension then acts as a bridge between the C-library code and the PHP script.

Get hands-on with 1400+ tech skills courses.