一、heredoc结构及用法
Heredoc 结构就象是没有使用双引号的双引号字符串,这就是说在 heredoc 结构中单引号不用被转义。其结构中的变量将被替换,但在 heredoc 结构中含有复杂的变量时要格外小心。其对格式化输出内容时,比较有用 。具体其有以下特点:
1、开始标记和结束标记使用相同的字符串,通常以大写字母来写。
2、开始标记后不能出现空格或多余的字符。
3、结束标记必须顶头写,不能有缩进和空格,且在结束标记末尾要有分号 。
4、位于开始标记和结束标记之间的变量可以被正常解析,但是函数则不可以。在heredoc中,变量不需要用连接符.或,来拼接 。
如:
<?php
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
/* 含有变量的更复杂示例 */
class foo
{
var $foo ;
var $bar ;
function foo ()
{
$this -> foo = 'Foo' ;
$this -> bar = array( 'Bar1' , 'Bar2' , 'Bar3' );
}
}
$foo = new foo ();
$name = 'MyName' ;
echo <<<EOT
My name is " $name ". I am printing some {$foo->foo} .
Now, I am printing some {$foo->bar [ 1 ]} .
This should print a capital 'A': \x41
EOT;
?>
以上例程会输出:
My name is "MyName". I am printing some Foo.
Now, I am printing some Bar2.
This should print a capital 'A': A
PS:1、heredoc 结构中含有复杂的变量时要格外小心,Heredoc输出中最好使用大括号{}来明确你的变量
2、在 PHP 5.3.0 以后,也可以用 Heredoc 结构来初始化静态变量和类的属性和常量;
3、自 PHP 5.3.0 起还可以在 Heredoc 结构中用双引号来声明标识符;
二、nowdoc结构及用法
在 PHP 5.3.0 及其以后的版本中增加了nowdoc结构,其用法和heredoc相同,不同的是Nowdoc 结构是类似于单引号字符串的。nowdoc 中不进行解析操作。这种结构很适合用于嵌入 PHP 代码或其它大段文本而无需对其中的特殊字符进行转义。与 SGML 的 结构是用来声明大段的不用解析的文本类似,nowdoc 结构也有相同的特征。
一个 nowdoc 结构也用和 heredocs 结构一样的标记 <<<, 但是跟在后面的标识符要用单引号括起来,即 <<<'EOT'。
例如:now结构中复杂变理的示例
<?php
$str = <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
EOD;
/* 含有变量的更复杂的示例 */
class foo
{
public $foo;
public $bar;
function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'MyName';
echo <<<'EOT'
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': x41
EOT;
?>
其输出为:
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': x41
PS:不象 heredoc 结构,nowdoc 结构可以用在任意的静态数据环境中,最典型的示例是用来初始化类的属性或常量