PHP Keywords: __halt_compiler()

15 February 2019 - 9:23pm

Welcome to my series on every PHP keyword and its usage. Today's item: __halt_compiler().

It looks like a function, but it's actually a language construct. I've never used it, and I expect that most PHP developers won't either.

Its primary purpose seems to be for mixing PHP code with other file types (such as zipped installation data), which may help if you're trying to create a single-file install.

In most cases, it would be more effective to package multiple files up into a Phar archive, rather than attempting to combine code and data into a single PHP file.

Usage

Note: Since this isn't something I've used before, I'm taking the example straight from the PHP docs.

<?php
// open this file
$fp = fopen(__FILE__, 'r');

// seek file pointer to data
fseek($fp, __COMPILER_HALT_OFFSET__);

// and output it
var_dump(stream_get_contents($fp));

// the end of the script execution
__halt_compiler();

Installation data goes here. Nothing past this point will cause a syntax error in the PHP script.

As you can see, extra data is just dropped right at the end. The example also uses the __COMPILER_HALT_OFFSET__ magic constant, which will get the position of the first byte after the compiler has been halted, allowing you to easily separate the data from the PHP code.