Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

ความแตกต่าง echo, print, print_r ใน PHP

ทั้งสามใช้แสดง Output แต่มีจุดประสงค์และพฤติกรรมต่างกัน

echo - Language Construct (ไม่ใช่ Function)

  • ไม่มี Return Value (void)
  • รับ Parameter หลายตัวได้: echo 'a', 'b', 'c';
  • เร็วกว่า print เล็กน้อย
  • ไม่สามารถใช้ใน Expression ได้
echo 'Hello', ' ', 'World'; // Hello World
// echo 'Hello' . ' ' . 'World'; // Concatenation ก่อน (ช้ากว่าเล็กน้อย)

// ❌ ไม่ได้: $result = echo 'test'; // Parse Error

print - Language Construct (Return 1 เสมอ)

  • มี Return Value เสมอคือ 1
  • รับ Parameter เดียวเท่านั้น
  • ใช้ใน Expression ได้
  • ช้ากว่า echo เล็กน้อย
$result = print 'Hello'; // พิมพ์ Hello, $result = 1

// ใช้ใน Expression ได้
$success = print 'Operation completed'; // $success = 1

// Ternary
$verbose && print "Debug info\n"; // Short-circuit

print_r - Function (สำหรับ Debug/Inspect Variable)

  • แสดงโครงสร้าง Variable (Array, Object) Human-readable
  • มี Parameter ที่ 2: $return = false - ถ้า true จะ Return String แทนการ Print
  • แสดง Protected/Private Properties ของ Object (PHP 5+)
$arr = ['name' => 'John', 'age' => 30, 'skills' => ['PHP', 'MySQL']];

print_r($arr);
/* Output:
Array
(
    [name] => John
    [age] => 30
    [skills] => Array
        (
            [0] => PHP
            [1] => MySQL
        )
)
*/

// Return String
$output = print_r($arr, true); // คืนค่า String แทนการ Print

var_dump() - Debug ขั้นสูง

  • แสดง Type และ Length ด้วย
  • แสดง Private/Protected Properties
  • ไม่มี Return Parameter (ต้องใช้ Output Buffering)
var_dump($arr);
/* Output:
array(3) {
  ["name"]=>
  string(4) "John"
  ["age"]=>
  int(30)
  ["skills"]=>
  array(2) {
    [0]=>
    string(3) "PHP"
    [1]=>
    string(5) "MySQL"
  }
}
*/

var_export() - Valid PHP Code

  • แสดง Output ที่เป็น Valid PHP Code
  • มี Parameter Return String
  • เหมาะสำหรับ Generate Config/Cache File
$code = var_export($arr, true);
// $code = 'array (\n  \'name\' => \'John\',\n  \'age\' => 30,\n  \'skills\' => \n  array (\n    0 => \'PHP\',\n    1 => \'MySQL\',\n  ),\n)'

// ใช้งาน
file_put_contents('config.php', '

สรุปตารางเปรียบเทียบ

Featureechoprintprint_rvar_dumpvar_export
TypeLanguage ConstructLanguage ConstructFunctionFunctionFunction
Return ValueNone (void)1 (int)bool (true) หรือ StringNone (void)bool (true) หรือ String
ParametersMultipleSingle1-2Multiple1-2
ใช้ใน Expression❌✅✅ (with $return=true)❌✅ (with $return=true)
FormatRaw StringRaw StringStructured (Human)Structured + Type/LenValid PHP Code
ใช้สำหรับOutput ทั่วไปRare (Expression)Debug Array/ObjectDebug DetailedCode Generation

Best Practice

  • Output HTML/Template: ใช้ echo (หรือ Short Tag )
  • Debug Development: ใช้ var_dump() หรือ dump() (Symfony/Laravel Helper)
  • Log/Store Structure: ใช้ var_export($var, true) หรือ json_encode()
  • Production: ไม่ควรมี print_r/var_dump ค้างอยู่