字符串高级进阶:Nowdoc、Heredoc

| 选择喜欢的代码风格  

Nowdoc 语法


直接看 PHP Nowdoc 实例:

<?php
$str = <<<'EOD'             // 用<<<来初始化,注意这里有单引号!
Example of string
spanning multiple lines
using nowdoc syntax.
$a does not parse.
EOD;                        // 'EOD'必须在新的一行上,并在最左边

/**
 * 输出:
 *
 * Example of string
 * spanning multiple lines
 * using nowdoc syntax.
 * $a does not parse.
 */

推荐更多阅读:

Heredoc 语法


<?php
$a = 'Variables';

$str = <<<EOD               // 用<<<初始化
Example of string
spanning multiple lines
using heredoc syntax.
$a are parsed.
EOD;                        // 同上,这里变量$a可以被解析

/**
 * 输出:
 *
 * Example of string
 * spanning multiple lines
 * using heredoc syntax.
 * Variables are parsed.
 */

推荐更多阅读:

Note:不象 heredoc 结构,nowdoc 结构可以用在任意的静态数据环境中,最典型的示例是用来初始化类的属性或常量。

这句话是什么意思呢?看代码:

<?php
class foo {
    public $bar = <<<'EOT'
bar
EOT;
}
?>


发表评论