Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent construct in PHP to Ruby's `__END__` or Perl's `__DATA__`

I'm using PHP from the command line and I'm trying to embed data into a source code file. I can do it in Ruby using the __END__ construct and in Perl using the __DATA__ construct, but I can't seem to find a way to do it in PHP. The goal is to be able to embed data in the PHP file, and then during execution, read the data into an array for processing. How can I do this in PHP? Including the data in a separate file is not really a good option due to the way the data and file execution are set up.

like image 436
Bill_B Avatar asked Aug 16 '11 19:08

Bill_B


3 Answers

You can use __halt_compiler() whose purpose is to, as the name says, halt the compiler precisely for the purpose of embedding data into the remainder of the file.

A basic example would be:

<?php

// Do something boring here

$data = file_get_contents(__FILE__, FALSE, NULL, __COMPILER_HALT_OFFSET__);
$obj  = json_decode($data, TRUE);
echo $obj['message'];

__halt_compiler();
{"status":"example", "message":"hello, __halt_compiler!"}

The output, as one would expect, is hello, __halt_compiler!

like image 110
salathe Avatar answered Oct 31 '22 20:10

salathe


Use the __halt_compiler() construct:

<?php

echo 'hello!';
__halt_compiler();
echo 'bar''; this will not cause a parse error
like image 34
netcoder Avatar answered Oct 31 '22 22:10

netcoder


you can use __halt_compiler() and embed data after that line of code. There is excellent example in the documentation.

like image 32
Maxim Krizhanovsky Avatar answered Oct 31 '22 20:10

Maxim Krizhanovsky