Wednesday, February 24, 2010

PHP: [Strings] Heredoc and Nowdoc


While reviewing PHP, I just discovered two new ways to handle strings.The heredoc and nowdoc.

Heredoc behaves like a double-quoted string and values inside are being parsed. You can use heredoc for embedding HTML codes.

sample:


<?php

$strString=<<< EOS
some strings
another line
EOS;

echo $strString;

?>



output:


some strings another line


the output is printed in 1 line because i didn't put a < br > in the sample codes.


Nowdoc behaves like single-quoted strings and no parsing is done inside a nowdoc.Nowdoc is good for embedding PHP code or other large blocks of text without the need for escaping.

sample:


<?php

$name="mel";
$month=2;

echo <<<'EOS'
Hi my name is $name.
My blog is $month months old.
EOS;
?>



output:


Hi my name is $name.
My blog is $month months old.



For further reading please visit http://php.net/manual/en/language.types.string.php

No comments:

Post a Comment

You might also like:


Related Posts Plugin for WordPress, Blogger...