Php中heredoc與nowdoc的使用方法

一、heredoc的結構和用法

Heredoc 結構就像是沒有使用雙引號的雙引號字符串,這就是說在 heredoc 結構中單引號不用被轉義。其結構中的變量將被替換,但在 heredoc 結構中含有複雜的變量時要格外小心。其對格式化輸出內容時,比較有用 。具體其有以下特點:

1、開始標記和結束標記使用相同的字符串,通常以大寫字母來寫。

2、開始標記後不能出現空格或多餘的字符。

3、結束標記必須頂頭寫,不能有縮進和空格,且在結束標記末尾要有分號 。

4、位於開始標記和結束標記之間的變量可以被正常解析,但是函數則不可以。在heredoc中,變量不需要用連接符.或,來拼接 。

如:

function outputhtml()
{
 //自 PHP 5.3.0 起還可以在 Heredoc 結構中用雙引號來聲明標識符,所以開頭這句也可以寫爲echo <<<"EOT"
echo <<<EOT
   <html>
   <head><title>主頁</title></head>
   <body>主頁內容</body>
   </html>
EOT;
}
outputhtml();

在這裏不用像php那樣,echo ““…. 那樣去輸出html代碼,也省去了每行的引號

二、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

具體可以和heredoc中的作下比較,在heredoc中,變量會被正常解析。x41也會被解析也A 。

轉載自:http://www.361way.com/php-heredoc-nowdoc/3008.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章