Home >Backend Development >PHP Tutorial >php heredoc 与 nowdoc
In the development of PHP we will often use html, sometimes it is a large section of html. It is very inconvenient to write html directly in PHP, I believe many My classmates have all encountered it, don’t worry about the delimiters heredoc and nowdoc in PHP will help us, so let’s take a look!
php heredoc and nowdoc
heredoc structure
heredoc syntax structure:<< <. After the operator, provide an identifier and then a newline. Next is the string itself, and finally the previously defined identifier is used as the end mark.
<?php $content = <<<FDIPZONE <html> <head> <title>test</title> </head> <body> <p><img src="http://www.csdn.net/css/logo.png"></p> <p><a href='http://blog.csdn.net/fdipzone'>blog</a></p> </body> </html> FDIPZONE; echo $content; ?>
The heredoc structure cannot be used to initialize properties of a class. 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 = '123'; public $a = <<<FDIPZONE $var FDIPZONE; } $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 = '123'; $content = <<<FDIPZONE $var time(); FDIPZONE; echo $content; // 123 time(); ?>
nowdoc structure
nowdoc syntactic structure is very similar to the heredoc structure, but no parsing operation is performed in nowdoc. This structure is very suitable for embedding php code or other large pieces of text without escaping the special characters.
nowdoc The same tags <<< as in the heredoc structure, but the following identifier must be enclosed in single quotes, i.e. <<<'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 = '123'; $content = <<<'FDIPZONE' $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 class attributes or constants. The following example will not go wrong, you can compare it with the heredoc example.
<?php class test{ public $a = <<<'FDIPZONE' $var FDIPZONE; } $obj = new test(); echo $obj->a; ?>
The above is the entire content of PHP heredoc and nowdoc. I hope it can be helpful to everyone.
Related recommendations:
Are the Heredoc and Nowdoc structures in PHP strings commonly used?
#PHP scalar type - string, how does Heredoc represent it?
The above is the detailed content of php heredoc 与 nowdoc. For more information, please follow other related articles on the PHP Chinese website!