php 中的單引號 雙引號 反引號的作用

來源:互聯網
上載者:User

字串的寫法

字串以單、雙或倒引號圍住分別有不同的義意。
單引號
例如:
$str = 'An apple a day keeps the docter away.'
當字串出現 ' 符號時,必須加上:
'I'm wing'
應改成:
'I'm wing'
才對,其中 ' 即稱為跳脫字元 (escape character)。

雙引號

以雙引號圍住的字串 PHP 會對該字串做 variable interpolation 的動作,亦即做變數的取代:
$name = "Wing";
echo 'Name: $name';
echo "Name: $name";
執行結果為:
Name: $name
Name: Wing
在雙引號裡的字串如果有 $ (dollar sign),只要改成跳脫字元的寫法即可:
$total = 12000
echo "Total: $ $total"; //輸出 Total: $ 12000
在做 variable interpolation 時,變數名稱是以一個以上空格做為界線,例如:
$n_file = 5;
if ($n_file == 1) {
echo "There are $n_file.";
} else {
echo "There are $n_files.";
}
當 $n_file 不為 1 時,"There are $n_files." PHP 所看到的變數為 $n_files,而不是正確的 $n_file,所以必須改成:
$n_file = 5;
if ($n_file == 1) {
echo "There are $n_file.";
} else {
echo "There are {$n_file}s.";
}

單引號內的雙引號,或是雙引號內的單引號都視為有效字元,不需使用跳脫字元,例如:
echo "I'm a happy bird.";
echo 'I'm a happy "bird"!';
輸出結果為:
I'm a happy bird.
I'm a happy "bird"!

反引號

利用反引號可以執行 Unix 下的命令,並傳回執行結果。例如:
echo `ls -l *.txt`;
表示將 ls -l *.txt 命令的執行結果輸出,以反引號圍住的字串為要執行的 UNIX 指令。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.