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.
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!
Use the __halt_compiler()
construct:
<?php
echo 'hello!';
__halt_compiler();
echo 'bar''; this will not cause a parse error
you can use __halt_compiler() and embed data after that line of code. There is excellent example in the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With