Is it possible to use Heredoc with special characters in an array?

2

I have a multidimensional array, as the example below shows, but I wonder if I can use a Heredoc in it, would it be possible? Could I include special non-escaped characters if I can use Heredoc ?

$name_code = array
  (
  array("Nome", "HEREDOC"),
  );

Heredoc code that you intended to use in the array ()

strong>.

$script = <<<CODE
rand@#¨4key"'?></
CODE;

Below is my attempt, which failed.

$name_code = array
  (
  array("Nome", $script = <<<CODE
  rand@#¨4key"'?></
  CODE;),
  );
    
asked by anonymous 06.08.2016 / 18:38

2 answers

4

In principle, HEREDOC only ends when you find the string defined, at the beginning of the line and at most with; in the end when needed.

Correcting your case:

$name_code = array
  (
  array("Nome", <<<CODE
  rand@#¨4key"'?></
CODE
    ),
  );

See working at IDEONE .

Note: Your string is whitespace at beginning   rand@#¨4key"'?></

The greatest care is to select a string that does not repeat itself.

If you do not want the characters to be escaped, and there are no variable substitutions, what you are looking for is NEWDOC, see the single quotes:

$script = <<<'CODE'
rand@#¨4key"'?></
CODE;
  

Difference from HEREDOC to NOWDOC in PHP

Now, if you are going to get the binary data from somewhere to "mount" PHP, you may have other problems with special characters when reading the file. Then it would be necessary to use HEREDOC and escape the characters.

See a comparison on IDEONE .

    
06.08.2016 / 18:47
2

Maybe it's not the solution you want, but another alternative to look at would be to use __halt_compiler combined with file_get_contents .

See:

$name_code = array (
  array(
   "Nome", file_get_contents(__FILE__, null, null, __COMPILER_HALT_OFFSET__)),
);

__halt_compiler();

Posso botar qualquer coisa aqui! $#<?php não vai ser processado ?>

You can learn more about __halt_compiler in this great answer from the user @gmsantos .

    
06.08.2016 / 18:58