Posted By

Snaver on 07/12/10


Tagged

php strings


Versions (?)

ENDOFSTRING PHP Strings


 / Published in: PHP
 

Here's a handy (relatively undocumented) tip. PHP supports the following method of assigning strings (borrowed from Perl)

  1. $string = <<<ENDOFSTRING
  2. This is a string
  3.  
  4. It can include both 'single' and "double" quotes
  5. without needing to escape them. However, $variables
  6. will still be interpolated as they are in double
  7. quoted strings. Complex variable expressions such as
  8. {$array['element']} or {$object->property} can also
  9. be included and will be evaluated if they are included
  10. in curly braces (they may work without curly braces
  11. but I tend to include them for added clarity). The
  12. string will terminate with whatever you specified
  13. at the start like this:
  14. ENDOFSTRING;

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: Vordreller on July 12, 2010

The 3 < signs are necessary?

Posted By: shaunduncan on July 13, 2010

This is known as HEREDOC syntax (http://bit.ly/j5IAU) ...it's useful for very long bits of text, but not great at all for performance. What is generally better is to use single quotes for strings and append variables that way the parser doesn't have to search the entire string first for variables (although you lose the ability to not escape double and single quotes). Then again, if you plan on just echoing back the entire string, you don't have to make an call at all...and in fact it works great since the php parser will completely ignore it:


his is a string 
 
It can include both 'single' and "double" quotes 
without needing to escape them. However, $variables 
will still be interpolated as they are in double 
quoted strings. Complex variable expressions such as 
 or  can also 
be included and will be evaluated if they are included 
in curly braces (they may work without curly braces 
but I tend to include them for added clarity). The 
string will terminate with whatever you specified 
at the start like this:

Posted By: shaunduncan on July 13, 2010

The above snip should be:

<?php ...some code... ?>
This is a string 

It can include both 'single' and "double" quotes 
without needing to escape them. However, $variables 
will still be interpolated as they are in double 
quoted strings. Complex variable expressions such as 
<?php echo $array['element']; ?> or <?php echo $object->property ?> can also 
be included and will be evaluated if they are included 
in curly braces (they may work without curly braces 
but I tend to include them for added clarity). The 
string will terminate with whatever you specified 
at the start like this:
<?php ...more code... ?>

You need to login to post a comment.