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

ความแตกต่างระหว่าง $ และ $$ ใน PHP (Variable Variables)

ตัวดำเนินการ $ และ $$ ใน PHP มีความหมายต่างกันอย่างสิ้นเชิง

$ - ตัวดำเนินการ Variable ปกติ

ใช้ประกาศและเข้าถึง Variable ตามปกติ

$name = 'John';
$age = 25;
$message = 'Hello World';

$$ - Variable Variables (ตัวแปรที่ชื่อมาจากค่าของอีกตัวแปร)

$$var หมายถึง Variable ที่ชื่อเท่ากับค่าของ $var

$varName = 'message';
$message = 'Hello World';

echo $varName;   // message
echo $$varName;  // Hello World (เพราะ $$varName = $message)

ตัวอย่างสมบูรณ์

";
echo $$welcome;   // Output: Welcome to Tutorialspoint

// การทำงาน:
// 1. $welcome = "message"
// 2. $$welcome = $message (เพราะค่า $welcome คือ "message")
// 3. $message = "Welcome to Tutorialspoint"
// 4. ดังนั้น $$welcome = "Welcome to Tutorialspoint"
?>

การใช้งานจริง (Use Cases)

1. Dynamic Form Processing

// $_POST = ['field_name' => 'email', 'field_value' => 'user@example.com']
$fieldName = $_POST['field_name'];  // 'email'
$fieldValue = $_POST['field_value']; // 'user@example.com'

// สร้าง Variable ชื่อ $email มีค่า 'user@example.com'
$$fieldName = $fieldValue;

echo $email; // user@example.com

2. Dynamic Object Property

$obj = new stdClass();
$propName = 'dynamicProperty';
$propValue = 'Some Value';

$obj->$propName = $propValue; // Object Property Variable
echo $obj->dynamicProperty; // Some Value

3. Array to Variables (Extract-like)

$data = ['title' => 'Hello', 'content' => 'World'];

foreach ($data as $key => $value) {
    $$key = $value;
}

echo $title;   // Hello
echo $content; // World

// หมายเหตุ: ใช้ extract($data) แทนได้ (แต่ extract มี Security Risk)

⚠️ ข้อควรระวังและ Best Practices

  • Security Risk: ไม่ควรใช้กับ User Input โดยตรง (Variable Injection)
  • Readability: Code ยากต่อการอ่านและ Debug
  • Modern Alternative: ใช้ Array/Collection แทน Variable Variables
  • PHP 8.2+: Dynamic Properties ถูก Deprecated ใน Class

ตัวอย่างอันตราย (อย่าทำแบบนี้)

// อันตราย! User สามารถสร้าง Variable ใดๆ ได้
foreach ($_GET as $key => $value) {
    $$key = $value; // หาก ?_SESSION=hacked -> $_SESSION ถูก Overwrite!
}

// ปลอดภัยกว่า: Whitelist
$allowed = ['name', 'email', 'age'];
foreach ($allowed as $key) {
    if (isset($_GET[$key])) {
        $$key = $_GET[$key];
    }
}