PHP 中的單引號 (') 和雙引號 (") 具有創建字串的相同主要目的,但在變數插值和轉義序列方面它們的行為不同。
單引號按字面意思對待其中的所有內容,只有兩個例外:
$name = "John"; echo 'Hello $name'; // Output: Hello $name echo 'I\'m learning PHP'; // Output: I'm learning PHP
雙引號處理多個轉義序列,最重要的是,解析字串內的變數和表達式:
$name = "John"; echo "Hello $name"; // Output: Hello John echo "Array value: {$array['key']}"; // Complex expressions need curly braces
讓我們透過一些基準來檢查效能差異:
$name = "John"; $iterations = 1000000; // Test single quotes $start = microtime(true); for ($i = 0; $i < $iterations; $i++) { $string = 'Hello ' . $name; } $single_quote_time = microtime(true) - $start; // Test double quotes $start = microtime(true); for ($i = 0; $i < $iterations; $i++) { $string = "Hello $name"; } $double_quote_time = microtime(true) - $start; printf("Single quotes: %.6f seconds\n", $single_quote_time); printf("Double quotes: %.6f seconds\n", $double_quote_time);
當您執行此程式碼時,您通常會發現現代 PHP 版本中的差異很小。不過,有一些注意事項:
$sql = 'SELECT * FROM users WHERE status = "active"'; $html = '<div> <ol> <li>Use double quotes when: <ul> <li>You need variable interpolation</li> <li>You need escape sequences like \n, \t, etc. </li> </ul> </li> </ol> <pre class="brush:php;toolbar:false">$message = "Dear $userName,\nThank you for your order #$orderId";
這是一個更複雜的範例,顯示了行為差異:
$user = [ 'name' => 'John', 'age' => 30 ]; // Single quotes require concatenation $message1 = 'User ' . $user['name'] . ' is ' . $user['age'] . ' years old'; // Double quotes allow direct interpolation with curly braces $message2 = "User {$user['name']} is {$user['age']} years old"; // Both produce the same output: // User John is 30 years old
以上是單引號和雙引號:字串插值和效能的詳細內容。更多資訊請關注PHP中文網其他相關文章!