2-4: String Interpolation
Objectives
- Memahami perbedaan single quotes dan double quotes
- Mengenal escape sequences
- Menggunakan heredoc dan nowdoc
- Memahami string concatenation
Single vs Double Quotes
Ini adalah konsep penting di PHP yang sering bikin bingung pemula.
| Aspek | Double Quotes "..." | Single Quotes '...' |
|---|---|---|
| Variabel | Diparse — "Halo $nama" menampilkan nilai | Literal — 'Halo $nama' menampilkan $nama |
| Escape sequences | Diproses (\n, \t, dll) | Hanya \\ dan \' yang diproses |
| Kecepatan | Sedikit lebih lambat (negligible) | Lebih cepat untuk string literal |
| Gunakan saat | Perlu interpolation variabel | String tanpa variabel / literal |
Perbedaan Utama
<?php
$nama = "Andi";
// Double quotes - VARIABEL DIPARSE
echo "Halo, $nama"; // Halo, Andi
echo "Umur saya $umur"; // Umur saya 25 (jika $umur ada)
// Single quotes - LITERAL
echo 'Halo, $nama'; // Halo, $nama
echo 'Umur saya $umur'; // Umur saya $umur
?>
Variabel di dalam String
Simple Variable
<?php
$user = "Andi";
echo "Welcome, $user"; // ✅ Works
echo 'Welcome, $user'; // ❌ Shows literal $user
?>
Array Element
<?php
$users = ["Andi", "Budi", "Citra"];
echo "First user: $users[0]"; // First user: Andi
echo "Second user: {$users[1]}"; // Second user: Budi
echo "Last user: {$users[count($users)-1]}"; // Last user: Citra
// ⚠️ Tanpa braces, akan error atau hasil salah
// echo "$users[0]"; // Work (diperbolehkan)
// echo "$users0"; // ❌ PHP cari $users0 yang tidak ada!
?>
Object Property
<?php
class User {
public $name = "Andi";
}
$user = new User();
echo "Hello, {$user->name}"; // Hello, Andi
// ⚠️ Tanpa braces
// echo "$user->name"; // Work (diperbolehkan)
?>
Complex Expressions
Complex (curly) syntax {$...} di dalam string hanya mendukung variabel, properti objek, dan array access — bukan ekspresi aritmatika. "{$a + $b}" akan menghasilkan parse error. Untuk menampilkan hasil operasi, gunakan concatenation.
<?php
$a = 5;
$b = 10;
// ✅ Benar: concatenation untuk ekspresi
echo "Sum: " . ($a + $b); // Sum: 15
echo "Product: " . ($a * $b); // Product: 50
// ❌ Salah: complex syntax tidak mendukung operasi aritmatika
// echo "Sum: {$a + $b}"; // Parse error!
// ✅ Array access tetap didukung dalam braces
$fruits = ["apple", "banana"];
echo "First: {$fruits[0]}"; // First: apple
// Array function dalam braces juga TIDAK valid
// echo "Count: {count($fruits)}"; // Parse error!
echo "Count: " . count($fruits); // Count: 2
?>
Aturan praktis: di dalam "...", braces {} hanya untuk mengakses nilai (variabel {$var}, properti {$obj->prop}, array {$arr[0]}). Kalau kamu butuh memproses nilai (operasi, function call), keluarkan dari string dulu lalu gabung dengan . (concatenation).
Escape Sequences
Di Double Quotes
<?php
// Newline
echo "Baris 1\nBaris 2";
// Tab
echo "Kolom1\tKolom2\tKolom3";
// Backslash
echo "Path: C:\\xampp\\htdocs";
// Double quote
echo "Dia berkata: \"Halo semua!\"";
// Dollar sign (tampilkan literal $)
echo "Harga \$100";
// Unicode
echo "Unicode: \u{1F600}"; // Emoji 😀
?>
Di Single Quotes
<?php
// Hanya \\ dan \'
echo 'Path: C:\\xampp\\file'; // Path: C:\xampp\file
echo 'It\'s PHP'; // It's PHP
echo 'Garis miring: \\'; // Garis miring: \
// ⚠️ \n di single quotes TIDAK diproses jadi newline!
// echo 'Baris 1\nBaris 2';
// Output: Baris 1\nBaris 2 (literal!)
?>
Heredoc
Heredoc untuk string multiline dengan interpreted values.
<?php
$nama = "Andi";
$pekerjaan = "Developer";
$bio = <<<EOT
Informasi Personal:
-------------------
Nama: $nama
Pekerjaan: $pekerjaan
Skills: PHP, JavaScript, MySQL
Terima kasih!
EOT;
echo $bio;
/*
Output:
Informasi Personal:
-------------------
Nama: Andi
Pekerjaan: Developer
Skills: PHP, JavaScript, MySQL
Terima kasih!
*/
?>
Heredoc dengan Indentation
<?php
// ⚠️ Whitespace sebelum closing marker akan included!
$text = <<<EOT
Ini text.
Ini ada indent.
EOT;
// Error jika ada whitespace sebelum EOT;
?>
Solusi untuk indentation:
<?php
// PHP 7.3+ - bisa indent closing marker
$text = <<<EOT
Ini text dengan indent.
Bisa rapi di code!
EOT;
// PHP < 7.3 - closing marker harus di column 0
$text = <<<EOT
Ini text.
EOT;
?>
Nowdoc
Nowdoc untuk string multiline yang literal (tidak diparse).
<?php
$nama = "Andi";
// Sekarang $nama TIDAK diparse
$sql = <<<'EOT'
SELECT * FROM users
WHERE name = '$nama'
AND status = 'active'
EOT;
echo $sql;
/*
Output:
SELECT * FROM users
WHERE name = '$nama'
AND status = 'active'
*/
?>
Perbandingan: Quotes vs Heredoc vs Nowdoc
<?php
$name = "Andi";
?>
| Method | Parsed? | Multiline? | Use Case |
|---|---|---|---|
'single' | ❌ | ❌ | Literal string |
"double" | ✅ | ❌ | String dengan variabel |
<<<EOT (heredoc) | ✅ | ✅ | Long text, SQL, HTML |
<<<'EOT' (nowdoc) | ❌ | ✅ | Code examples, literal text |
String Concatenation
Operator . (dot) untuk menggabungkan string.
<?php
// Basic concatenation
$first = "Hello";
$last = "World";
$full = $first . " " . $last;
echo $full; // Hello World
// Concatenation assignment
$text = "Hello";
$text .= " ";
$text .= "World";
echo $text; // Hello World
// Multiple concatenations
$sql = "SELECT " . "id, " . "name " . "FROM users";
// SELECT id, name FROM users
?>
Concatenation vs Double Quotes
<?php
$first = "John";
$last = "Doe";
// Concatenation
$name1 = $first . " " . $last;
// Double quotes
$name2 = "$first $last";
// Keduanya output: "John Doe"
?>
Performance: Untuk string sederhana dengan variabel, double quotes lebih readable. Untuk operasi kompleks atau multiple concatenations, concatenation dengan . lebih jelas.
Common Patterns
1. Building HTML
<?php
$title = "Welcome";
$content = "Hello World";
$html = <<<HTML
<div class="container">
<h1>{$title}</h1>
<p>{$content}</p>
</div>
HTML;
?>
2. Building SQL
<?php
$table = "users";
$column = "name";
$value = "Andi";
// ❌ RENTAN SQL INJECTION - jangan lakukan ini di production!
$sql = "SELECT * FROM $table WHERE $column = '$value'";
// ✅ Menggunakan prepared statement (production safe)
$sql = <<<SQL
SELECT * FROM {$table}
WHERE {$column} = ?
SQL;
?>
3. Echo vs Print
<?php
// echo - lebih cepat, bisa multiple args
echo "Hello", " ", "World"; // Hello World
// print - return 1, hanya satu argumen
print "Hello World"; // Hello World
// Nilai return
$result = echo "text"; // ❌ Error - echo tidak return value
$result = print "text"; // ✅ 1 - print return 1
?>
Best Practices
-
Gunakan double quotes untuk variabel interpolation
- ✅
"Hello $name" - ❌
'Hello ' . $name
- ✅
-
Gunakan single quotes untuk literal string
- ✅
'Hello World' - ❌
"Hello World"
- ✅
-
Gunakan heredoc untuk string panjang
- ✅
<<<EOT ... EOT
- ✅
-
Escape special characters dengan backslash
- ✅
"Harga \$100" - ❌
"Harga $100"(PHP coba parse$100!)
- ✅
-
Untuk SQL, selalu gunakan prepared statements
- ❌
"SELECT * FROM users WHERE name = '$name'" - ✅ Prepared statement dengan
?placeholders
- ❌
Common Mistakes
<?php
// ❌ ERROR: Undefined variable
echo "Hello $name"; // Notice: Undefined variable: name
// ✅ FIX: Check existence
echo "Hello " . ($name ?? "Guest");
// ❌ ERROR: Unexpected T_VARIABLE
// $sql = "SELECT * FROM users WHERE name = '$name's friends'";
// ✅ FIX: Escape atau gunakan nowdoc
$sql = "SELECT * FROM users WHERE name = '{$name}s friends'";
// ❌ ERROR: Confusing braces
// $users = ["Andi", "Budi"];
// echo "$users[0] and $users[1]'s friend"; // Parse error!
// ✅ FIX: Proper braces
echo "{$users[0]} and {$users[1]}'s friend";
?>
Exercise
-
Prediksi output dari:
php$a = "Hello"; $b = 'Hello'; var_dump($a === $b); // ? -
Buat string multiline menggunakan heredoc yang berisi:
- Header dengan variabel $title
- List items dengan array loop
- Footer dengan $date
-
Apa perbedaan output dari:
phpecho "\$100"; // vs echo '$100'; -
Buat HTML card dengan heredoc:
php$card = <<<HTML <div class="card"> <h2>{$title}</h2> <p>{$description}</p> </div> HTML;
Summary
| Konsep | Penjelasan |
|---|---|
| Single quotes | Literal, hanya \\ dan \' diproses |
| Double quotes | Interpreted, variabel & escape sequences diproses |
| Heredoc | Multiline, interpreted, <<<EOT |
| Nowdoc | Multiline, literal, <<<'EOT' |
| Concatenation | . operator untuk gabung string |
Braces {} | Untuk complex variable expressions |
Gunakan single quotes untuk string tanpa variabel — lebih cepat dan signals intent bahwa string adalah literal. Gunakan double quotes hanya ketika kamu benar-benar butuh interpolation.
Klik tombol ini setelah menyelesaikan materi
Quiz Bab 2
Uji pemahamanmu tentang Variabel & Tipe Data