Home  >  Article  >  Backend Development  >  Introduction to heredoc and nowdoc in php (code example)

Introduction to heredoc and nowdoc in php (code example)

不言
不言forward
2019-02-18 14:04:521829browse

This article brings you an introduction to heredoc and nowdoc in PHP (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. helped.

heredoc structure

heredoc syntax structure: <<<. After the operator, provide an identifier and then a newline. Next comes the string itself, ending with the previously defined identifier.

<?php
$content = <<<FDIPZONE
<html>
<head>
<title>test</title>
</head>
<body>
<p>
<img src="http://www.csdn.net/css/logo.png"> 
</p>
<p><
a href=&#39;http://blog.csdn.net/fdipzone&#39;>blog</a> 
</p>
</body>
</html>
FDIPZONE;
echo $content;
?>

heredoc structure cannot be used to initialize class properties. As of PHP 5.3, this restriction only applies when the heredoc contains variables. The following example will go wrong.

<?php
class test{
public $var = &#39;123&#39;;
public $a = <<<FDIPZONE$varFDIPZONE;
}
$obj = new test();
echo $obj->a;
?>

In the heredoc structure, variables will be replaced, but methods will not. Be careful when containing complex variables.

<?php
$var = &#39;123&#39;;
$content = <<<FDIPZONE$var time();
FDIPZONE;
echo $content; // 123 time();
?>

nowdoc structure

The syntactic structure of nowdoc is very similar to the heredoc structure, but no parsing operation is performed in nowdoc. This structure is suitable for embedding PHP code or other large pieces of text without escaping special characters.

nowdoc has the same tags <<< as the heredoc structure, but the identifier following must be enclosed in single quotes , that is, <<< 'EOF'. All the rules for heredoc structures also apply to nowdoc structures, especially the rules for terminating identifiers. nowdoc was added after php5.3.

<?php
$var = &#39;123&#39;;
$content = <<<&#39;FDIPZONE&#39;$var time();
FDIPZONE;echo $content; // $var time(); 
$var没有被替换
?>

nowdoc structure can be used in any static data environment. The most typical example is to initialize properties or constants of a class. The following example will not go wrong, you can compare it with the heredoc example.

<?php
class test{
public $a = <<<&#39;FDIPZONE&#39;$varFDIPZONE;
}
$obj = new test();
echo $obj->a;
?>

The above is the detailed content of Introduction to heredoc and nowdoc in php (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete