在 PHP 中,使用 Heredoc 語法可以在字符串中方便地插入變量或執行代碼。Heredoc 語法非常類似于雙引號字符串語法,但是可以不必使用轉義字符來插入變量或特殊字符。
下面是一個簡單的例子,使用 Heredoc 語法輸出多行字符串和變量:
$name = 'John'; $age = 30; $str = <<<EOD My name is $name. I am $age years old. EOD; echo $str;以上代碼輸出:
My name is John.
I am 30 years old.
$arr = array('name' =>'John', 'age' =>30); $str = <<<EOD My name is {$arr['name']}. I am {$arr['age']} years old. EOD; echo $str;以上代碼輸出:
My name is John.
I am 30 years old.
$name = 'John'; $age = 30; $gender = 'male'; $str = <<<EOD {name} is a {age}-year-old {gender}. {if $age >= 18} He is an adult. {else} He is still a child. {/if} EOD; echo $str;以上代碼輸出:
John is a 30-year-old male.
He is an adult.