php中heredoc和nowdoc的使用方法

2021-06-29 16:47:44 字數 1818 閱讀 9536

heredoc技術,在正規的php文件中和技術書籍中一般沒有詳細講述,只是提到了這是一種perl風格的字串輸出技術。但是現在的一些論壇程式,和部分文章系統,都巧妙的使用heredoc技術,來部分的實現了介面與**的準分離,phpwind模板就是乙個典型的例子。

如下:<?php

$name = '淺水遊';

print <<

hello,$name!

eot;

?>

1.以<<開始標記開始,以end結束標記結束,結束標記必須頂頭寫,不能有縮排和空格,且在結束標記末尾要有分號。開始標記和開始標記相同,比如常用大寫的eot、eod、eof來表示,但是不只限於那幾個,只要保證開始標記和結束標記不在正文中出現即可

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

$v=2;

$a=

outputhtml();

就象heredoc結構類似於雙引號字串,nowdoc結構是類似於單引號字串的。nowdoc結構很象heredoc結構,但是nowdoc不進行解析操作 。 這種結構很適合用在不需要進行轉義的php**和其它大段文字。與sgml的結構是用來宣告大段的不用解析的文字類似,nowdoc結構也有相同的特徵。

乙個nowdoc結構也用和heredocs結構一樣的標記<<<,但是跟在後面的標誌符要用單引號括起來,就像<<<'eot'這樣。heredocs結構的所有規則也同樣適用於nowdoc結構,尤其是結束標誌符的規則。

example #2 heredoc結構的字串示例

<?php

$str = <<

class foo

}$foo = new foo();

$name = 'myname';

echo

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

example #6 nowdoc結構字串示例

<?php

$str = <<<'eod'

example of string

spanning multiple lines

using nowdoc syntax.

eod;

class foo

}$foo = new foo();

$name = 'myname';

echo <<<'eot'

my name is "$name". i am printing some$foo->foo.

now, i am printing some .

this should not print a capital 'a': \x41

eot;

?>

以上例程會輸出:

my name is "$name". i am printing some$foo->foo.

now, i am printing some .

this should not print a capital 'a': \x41

PHP中的heredoc和nowdoc的使用

heredoc 結構就象是沒有使用雙引號的雙引號字串,這就是說在 heredoc 結構中單引號不用被轉義。其結構中的變數將被替換,但在 heredoc 結構中含有複雜的變數時要格外小心。其對格式化輸出內容時,比較有用 具體其有以下特點 1.開始標記和結束標記使用相同的字串,通常以大寫字母來寫。2.開...

php中heredoc與nowdoc介紹

heredoc技術,在正規的php文件中和技術書籍中一般沒有詳細講述,只是提到了這是一種perl風格的字串輸出技術。但是現在的一些論壇程式,和部分文章系統,都巧妙的使用heredoc技術,來部分的實現了介面與 的準分離,phpwind模板就是乙個典型的例子。1.以 2.位於開始標qbcsj記和結束標...

php中heredoc的使用方法

svoting votes eos heredoc技術,在正規的php文件中和技術書籍中一般沒有詳細講述,只是提到了這是一種perl風格的字串輸出技術。1.以 開始標記開始,以end結束標記結束,結束標記必須頂頭寫,不能有縮排和空格,且在結束標記末尾要有分號。開始標記和開始標記相同,比如常用大寫的e...