fork download
  1. <?php
  2.  
  3. class Klass {
  4. // 被演算子(シリアライズする)
  5. private $a;
  6. // 被演算子(シリアライズする)
  7. private $b;
  8.  
  9. // 再計算が必要かどうかを表す(シリアライズしたくない)
  10. private $needCalc;
  11. // 計算結果(シリアライズしたくない)
  12. private $cache;
  13.  
  14. public function __construct($a, $b) {
  15. $this->a = $a;
  16. $this->b = $b;
  17. $this->needCalc = true;
  18. $this->cache = null;
  19. }
  20.  
  21. public function getResult() {
  22. if ($this->needCalc) {
  23. $this->cache = $this->calc();
  24. $this->needCalc = false;
  25. }
  26. return $this->cache;
  27. }
  28.  
  29. private function calc() {
  30. return $this->a + $this->b;
  31. }
  32.  
  33. public function __sleep() {
  34. // $this->a と $this->b だけをシリアライズしたい
  35. return array('a', 'b');
  36. }
  37.  
  38. public function __wakeup() {
  39. // シリアライズしなかったものの初期値
  40. $this->needCalc = true;
  41. $this->cache = null;
  42. }
  43. }
  44.  
  45. // インスタンス化およびキャッシング
  46. $obj = new Klass(42, 23);
  47. var_dump($obj);
  48. $obj->getResult();
  49. var_dump($obj);
  50.  
  51. // シリアライズ不要なフィールドは捨てられたか?
  52. $ser = serialize($obj);
  53. var_dump($ser);
  54.  
  55. // シリアライズしなかったフィールドに
  56. // 正しく初期値が与えられているか?
  57. $newObj = unserialize($ser);
  58. var_dump($newObj);
  59. $newObj->getResult();
  60. var_dump($newObj);
Success #stdin #stdout 0.02s 13064KB
stdin
Standard input is empty
stdout
object(Klass)#1 (4) {
  ["a:private"]=>
  int(42)
  ["b:private"]=>
  int(23)
  ["needCalc:private"]=>
  bool(true)
  ["cache:private"]=>
  NULL
}
object(Klass)#1 (4) {
  ["a:private"]=>
  int(42)
  ["b:private"]=>
  int(23)
  ["needCalc:private"]=>
  bool(false)
  ["cache:private"]=>
  int(65)
}
string(56) "O:5:"Klass":2:{s:8:"Klassa";i:42;s:8:"Klassb";i:23;}"
object(Klass)#2 (4) {
  ["a:private"]=>
  int(42)
  ["b:private"]=>
  int(23)
  ["needCalc:private"]=>
  bool(true)
  ["cache:private"]=>
  NULL
}
object(Klass)#2 (4) {
  ["a:private"]=>
  int(42)
  ["b:private"]=>
  int(23)
  ["needCalc:private"]=>
  bool(false)
  ["cache:private"]=>
  int(65)
}