Skip to content

Chapter 4: Pages — To Echo or Not To Echo

Ringkasan

Video ini menjelaskan perbedaan fundamental antara echo dan return dalam PHP, serta cara mengetahui kapan harus pakai echo dengan fungsi WordPress.


Konsep: Echo vs Return

Membuat Function yang Echo

php
function doubleMe($x) {
    echo $x * 2;
}

doubleMe(5);  // Langsung output: 10
doubleMe(25); // Langsung output: 50
  • Function ini langsung menampilkan hasilnya ke halaman
  • Tidak perlu echo saat memanggil function

Membuat Function yang Return

php
function doubleMe($x) {
    return $x * 2;
}

doubleMe(25); // TIDAK output apa-apa! Nilai 50 hanya "disimpan" di memory
  • Function mengembalikan (return) nilai, tapi tidak menampilkan ke halaman
  • Kita harus secara eksplisit melakukan sesuatu dengan nilai tersebut

Cara Menggunakan Nilai Return

php
// 1. Echo ke halaman
echo doubleMe(25); // Output: 50

// 2. Simpan ke variabel
$magicalNumber = doubleMe(10); // $magicalNumber = 20

// 3. Gunakan di If statement
if (doubleMe(12) == 24) {
    echo "The function is performing math correctly";
}

Keunggulan Return: Composability

Function yang return bisa di-compose satu sama lain:

php
function doubleMe($x) {
    return $x * 2;
}

function tripleMe($x) {
    return $x * 3;
}

echo tripleMe(doubleMe(5));
// doubleMe(5) → return 10
// tripleMe(10) → return 30
// echo 30 → Output: 30

Rule of Thumb untuk WordPress Functions

Awalan FunctionBehaviorPerlu echo?Contoh
the_Langsung output/echo ke halaman❌ Tidakthe_title(), the_content(), the_ID()
get_Return nilai saja✅ Yaget_the_title(), get_the_ID(), get_permalink()

Contoh Praktis

php
// BENAR — the_title() langsung echo
the_title();

// BENAR — get_the_title() perlu echo
echo get_the_title(16);

// SALAH — double echo (output berantakan)
echo the_title();

// SALAH — tidak echo (tidak tampil apa-apa)
get_the_title(16);

Referensi Resmi

Jika tidak yakin apakah function echo atau return:

  • Codex (codex.wordpress.org)
  • Developer WordPress (developer.wordpress.org)

Website resmi ini menjelaskan setiap function: parameter, return value, dan contoh penggunaan.


Poin Penting

  • echo = menampilkan nilai ke halaman
  • return = mengembalikan nilai ke kode pemanggil (lebih fleksibel)
  • WordPress function dengan prefix the_ → langsung echo
  • WordPress function dengan prefix get_ → return value, perlu echo manual
  • Function yang return bisa digunakan di mana saja: variabel, if statement, argument function lain
  • Tidak perlu menghafal semua function — cek di documentation resmi WordPress