fork download
  1. <?php
  2.  
  3. class Klass implements Serializable {
  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 serialize() {
  34. return serialize(array($this->a, $this->b));
  35. }
  36.  
  37. public function unserialize($serialized) {
  38. $ar = unserialize($serialized);
  39. $this->a = $ar[0];
  40. $this->b = $ar[1];
  41. $this->needCalc = true;
  42. $this->cache = null;
  43. }
  44. }
  45.  
  46. // インスタンス化およびキャッシング
  47. $obj = new Klass(42, 23);
  48. var_dump($obj);
  49. $obj->getResult();
  50. var_dump($obj);
  51.  
  52. // シリアライズ不要なフィールドは捨てられたか?
  53. $ser = serialize($obj);
  54. var_dump($ser);
  55.  
  56. // シリアライズしなかったフィールドに
  57. // 正しく初期値が与えられているか?
  58. $newObj = unserialize($ser);
  59. var_dump($newObj);
  60. $newObj->getResult();
  61. var_dump($newObj);
Success #stdin #stdout 0.02s 13112KB
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(41) "C:5:"Klass":24:{a:2:{i:0;i:42;i:1;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)
}