haphpiness

These are things in PHP which make me genuinely_happy();

FFI — Call C Libraries Directly from PHP

PHP 7.4 introduced the Foreign Function Interface, letting you load shared libraries and call C functions directly — with no extension to compile, no PECL, and no separate process. This is the feature that reliably shocks people who dismissed PHP.

// Load the C math library and call cos() directly
$ffi = FFI::cdef(
    'double cos(double x);',  // C declaration
    'libm.so.6'               // shared library (Linux); 'libm.dylib' on macOS
);

echo $ffi->cos(M_PI);  // -1.0 — called at C speed

FFI can work with C structs, pointers, arrays, and callbacks. You can load any shared library installed on the system — libsodium, libgd, OpenCV, even custom `.so` files you compiled yourself.

// Define and use a C struct
$ffi = FFI::cdef('
    typedef struct {
        int x;
        int y;
    } Point;

    typedef struct {
        Point origin;
        int width;
        int height;
    } Rect;
');

$rect = $ffi->new('Rect');
$rect->origin->x = 10;
$rect->origin->y = 20;
$rect->width  = 100;
$rect->height = 50;

echo "{$rect->origin->x}, {$rect->origin->y}";  // 10, 20

For performance-critical inner loops, you can preload FFI definitions at startup via ffi.preload in php.ini, making the binding cost negligible. Projects like phpReactPHP and PHP-ML use FFI for exactly this.

Significance: Systems Access

FFI erases the boundary between PHP and the native world. Image processing, cryptography, hardware interfaces, and high-performance numerics are all accessible without leaving PHP. It turns PHP into a scripting layer for the entire C ecosystem.