ts2kva
Last Updated: February 25, 2016
·
2.347K
· rdosser

Use "__halt_compiler" to ... well, halt the PHP compiler

php

A little known "magic" method in php:

void __halt_compiler ( void )

Allows you so say "stop compiling beyond this point" in your php source code.

The main use of this is to allow you to embed data in the same file as the PHP source. For example, this script

<?php

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

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

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

// the end of the script execution
__halt_compiler();
foo! bar!
baz! bam!

Outputs the following:

foo! bar!
baz! bam!

Another use would be to allow a developer to insert temporary debugging statements into his code in a way that otherwise fail to compile. For example, if you have a set of if/then statements that you want to stick a temporary line or clause into, you could do this:

if($condition) {
    // do some work
}
var_dump($variable);
__halt_compiler();
else {
    // do some other work
}

Note that this can only be invoked in the top-level scope.

1 Response
Add your response

5398

Interesting... +1

over 1 year ago ·