React, Flux, GraphQL, Hack, HHVM...? All of this and more!
With WebAssembly and GraalVM language runtimes and barriers are falling down. PHP is no exception with the .NET runtime now being able to excute PHP using PeachPie for high performance.
Now Dmitry Stogov from Zend has extended the realm of PHP by allowing execution of embedded C code from PHP. This will allow full access to native C functions, variables as well as data structures.
The solution, PHP FFI, is provided as an experimental extension that requires a development version of the next minor release, PHP 7.3. The solution is nowhere near for production, but it is built on a solid foundations as it is using the FFI (Foreign Functions Interface) library, libffi, which allows high level languages to generate code.
All of this is wrapped into a simple API that allows developers to write inline C code within PHP scripts:
<?php
$libc = new FFI("
int printf(const char *format, ...);
char * getenv(const char *);
unsigned int time(unsigned int *);
typedef unsigned int time_t;
typedef unsigned int suseconds_t;
struct timeval {
time_t tv_sec;
suseconds_t tv_usec;
};
struct timezone {
int tz_minuteswest;
int tz_dsttime;
};
int gettimeofday(struct timeval *tv, struct timezone *tz);
", "libc.so.6");
$libc->printf("Hello World from %s!\n", "PHP");
var_dump($libc->getenv("PATH"));
var_dump($libc->time(null));
$tv = $libc->new("struct timeval");
$tz = $libc->new("struct timezone");
$libc->gettimeofday($tv, $tz);
var_dump($tv->tv_sec, $tv->tv_usec, $tz);
?>
…will generate an output as follows:
Hello World from PHP! string(135) "/usr/lib64/qt-3.3/bin:/usr/lib64/ccache:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/home/dmitry/.local/bin:/home/dmitry/bin" int(1523617815) int(1523617815) int(977765) object(CData)#3 (2) { ["tz_minuteswest"]=> int(-180) ["tz_dsttime"]=> int(0) }
In addition to reliability and bugs, FFI data structure access is slow at this point, it is around 4 times as slow as accessing raw PHP arrays and objects. At this stage use of FFI for speed is not feasible, but memory saving can be substancial.
Performance will improve as PHP FFI stabilizes and effort is put into optimizations. Follow PHP FFI development on GitHub: github.com/dstogov/php-ffi
Tweet