Definition and Usage
ใน PHP string data type คือลำดับอักขระที่ไม่ใช่ตัวเลข (non-numeric sequence of characters) อักขระใดๆ ใน ASCII set สามารถเป็นส่วนหนึ่งของ string ได้ PHP ไม่รองรับ UNICODE
ใน PHP literal representation ของ string สามารถทำได้ด้วย single quotes, double quotes, heredoc syntax และ nowdoc syntax
ไวยากรณ์
// Literal assignment of string value to variable $var = 'Hello World'; // Single quotes $var3 = "Hello World"; // Double quotes
เพื่อฝังอักขระ single quote ภายใน single quoted string ให้เติม \ นำหน้า เช่นเดียวกัน เพื่อฝัง backslash ใน single quoted string ให้เติม backslash เพิ่ม Escape sequence characters อื่นๆ เช่น \n ไม่มีความหมายพิเศษ
Double quoted string จัดการ escape sequences ต่อไปนี้ด้วยความหมายพิเศษ:
| Sequence | Meaning |
|---|---|
| \n | linefeed |
| \r | carriage return |
| \t | horizontal tab |
| \v | vertical tab (since PHP 5.2.5) |
| \e | escape (since PHP 5.4.4) |
| \f | form feed (since PHP 5.2.5) |
| \\ | backslash |
| \$ | dollar sign |
| \" | double-quote |
Heredoc string เริ่มต้นด้วย <<< symbol ตามด้วย identifier ที่ผู้ใช้เลือก จากบรรทัดถัดไป ลำดับอักขระหลายบรรทัดที่อาจมี escape sequences ข้างต้น บรรทัดสุดท้ายควรมี heredoc identifier เดียวกันจบด้วย semicolon
// Heredoc assignment of string value to variable public $var = <<< XYZ Hello World Welcome to Tutorialspoint XYZ;
Nowdoc strings คล้าย heredoc strings ความแตกต่างคือ identifier ต้องอยู่ใน single quotes และ escape sequences ภายใน nowdoc string ไม่ถูก parse และปรากฏ as-is
// Nowdoc assignment of string value to variable public $var = <<< 'XYZ' Hello World Welcome to Tutorialspoint XYZ;
PHP Version
การใช้สัญลักษณ์คั่น "_" พร้อมใช้งานตั้งแต่ PHP 7.4.0
ตัวอย่างต่อไปนี้แสดง single quoted string Escape sequence \n ไม่ถูก parse และปรากฏ as-is
ตัวอย่าง
<?php $var = 'Hello World.\n Welcome to Tutorialspoint'; echo $var; ?>
ผลลัพธ์
จะได้ผลลัพธ์ดังนี้
Hello World.\n Welcome to Tutorialspoint
ตัวอย่างนี้ double quoted string Escape sequence \n ถูก parse และข้อความปรากฏ 2 บรรทัด
ตัวอย่าง
<?php $var = "Hello World.\n Welcome to Tutorialspoint"; echo $var; ?>
ผลลัพธ์
จะได้ผลลัพธ์ดังนี้
Hello World. Welcome to Tutorialspoint
ตัวอย่างนี้แสดงวิธีใช้ Heredoc และ Nowdoc syntax สำหรับ string representation
ตัวอย่าง
<?php // Heredoc $var = <<< STR Hello World Welcome to Tutorialspoint STR; echo $var . "\n"; // Nowdoc $var = <<< 'STR' Hello World Welcome to Tutorialspoint STR; echo $var; ?>
ผลลัพธ์
จะได้ผลลัพธ์ดังนี้
Hello World Welcome to Tutorialspoint Hello World Welcome to Tutorialspoint
ตัวอย่างนี้แสดงค่าตัวแปรถูกแทนที่ใน heredoc string Nowdoc string ไม่ทำ substitution
ตัวอย่าง
<?php $name = "Mahesh"; $var = <<< STR Hello $name Welcome to Tutorialspoint STR; echo $var . "\n"; // Nowdoc $var = <<< 'STR' Hello $name Welcome to Tutorialspoint STR; echo $var; ?>
ผลลัพธ์
จะได้ผลลัพธ์ดังนี้
Hello Mahesh Welcome to Tutorialspoint Hello $name Welcome to Tutorialspoint