Using FFI in an Application

Learn how FFI methods help developers execute C-language code in a PHP application.

Any shared C library (generally with a *. so extension) can be included in a PHP application using the FFI extension. If we plan to work with any of the core PHP libraries or libraries produced when PHP extensions are installed, it’s important to note that we have the ability to modify the behavior of the PHP language itself.

Before we examine how that works, let’s first have a look at incorporating an external C library into a PHP script using the FFI extension.

Integrating an external C library into a PHP script

For the purposes of illustration, we use a simple function that might have originated from a Computer Science 101 (CS101) class: the famous bubble sort. This algorithm is widely used in beginner’s computer science classes because it’s easy to follow.

Note: The bubble sort is an extremely inefficient sort algorithm and has long been superseded by faster sorting algorithms such as the shell sort, quick sort, or merge sort algorithms.

Get hands-on with 1200+ tech skills courses.