ทั้ง json_encode และ serialize ใช้เก็บ PHP Array/Object ลง String (Database, File, Cache, Session) แต่มีคุณสมบัติต่างกัน
สรุปความแตกต่าง
| Feature | json_encode | serialize |
|---|---|---|
| Format | JSON (Standard, Human-readable) | PHP Serialized String (Binary-safe) |
| Portability | สูงมาก (ทุกภาษาอ่านได้) | ต่ำ (เฉพาะ PHP) |
| Performance (Encode) | เร็วกว่า | ช้ากว่า |
| Performance (Decode) | เร็วกว่า | ช้ากว่า |
| Object Class Info | ไม่เก็บ (กลายเป็น stdClass) | เก็บ Class Name |
| __sleep/__wakeup | ไม่รองรับ | รองรับ |
| Recursive/Reference | Error (Circular Reference) | รองรับ (Pointer) |
| Resource/Closure | Error | Error (แต่可通过 __sleep exclude) |
| Binary Data | ต้อง Base64/UTF-8 Encode | รองรับโดยตรง |
| Deeply Nested | ช้าลง/Stack Overflow | ดีกว่า |
เมื่อไหร่ควรใช้ json_encode
- สื่อสารกับ Frontend/JavaScript/API
- เก็บใน Database (JSON Column: MySQL 5.7+, PostgreSQL, MongoDB)
- Cache (Redis, Memcached) - Human Readable ตอน Debug
- Config File, Log File
- Interoperability กับภาษาอื่น
$array = ['name' => 'John', 'email' => 'john@example.com', 'tags' => ['php', 'mysql']];
$json = json_encode($array, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
// {"name":"John","email":"john@example.com","tags":["php","mysql"]}
// Decode
$data = json_decode($json, true); // true = Associative Array
เมื่อไหร่ควรใช้ serialize
- Object ที่ต้อง Restore กลับเป็น Class เดิม (Class Name, Private/Protected Properties)
- ต้องการใช้
__sleep()(เลือก Property ที่จะ Serialize) และ__wakeup()(Initialize หลัง Unserialize) - Data มี Circular Reference
- Binary Data (Images, Files) - แต่อาจใหญ่เกิน ควรเก็บไฟล์แยก
- Legacy PHP (< 5.2) ที่ไม่มี json_encode
class User {
private $id;
private $name;
private $password; // ไม่ต้องการ Serialize
public function __construct($id, $name, $password) {
$this->id = $id;
$this->name = $name;
$this->password = $password;
}
public function __sleep() {
return ['id', 'name']; // Exclude password
}
public function __wakeup() {
// Re-initialize connection, decrypt, etc.
$this->password = '***HIDDEN***';
}
}
$user = new User(1, 'John', 'secret123');
$serialized = serialize($user);
// O:4:"User":2:{s:2:"id";i:1;s:4:"name";s:4:"John";}
$restored = unserialize($serialized);
// $restored เป็น User Object จริง พร้อม Private Properties
JsonSerializable Interface (PHP 5.4+)
ควบคุม JSON Output ของ Object
class ApiUser implements JsonSerializable {
private $id;
private $email;
private $passwordHash;
public function jsonSerialize(): array {
return [
'id' => $this->id,
'email' => $this->email,
// passwordHash ไม่รวม
];
}
}
$user = new ApiUser(1, 'john@example.com', 'hash');
echo json_encode($user); // {"id":1,"email":"john@example.com"}
Performance Tip: igbinary (Extension)
สำหรับ Serialize ที่เร็วกว่าและเล็กลง 50-70%
// Install: pecl install igbinary
$serialized = igbinary_serialize($data);
$data = igbinary_unserialize($serialized);
// ใช้กับ Redis/Memcached
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_IGBINARY);
คำแนะนำสรุป
- Default: json_encode - เร็ว, Portable, Readable, มาตรฐาน
- Object Complex: serialize - ต้อง Restore Class, Private Props, Sleep/Wakeup
- High Performance Cache: igbinary - เร็วกว่า serialize, ขนาดเล็กกว่า
- Database JSON Column: json_encode - Query ได้ด้วย JSON Functions