<?php
class Klass {
// 被演算子(シリアライズする)
private $a;
// 被演算子(シリアライズする)
private $b;
// 再計算が必要かどうかを表す(シリアライズしたくない)
private $needCalc;
// 計算結果(シリアライズしたくない)
private $cache;
public function __construct($a, $b) {
$this->a = $a;
$this->b = $b;
$this->needCalc = true;
$this->cache = null;
}
public function getResult() {
if ($this->needCalc) {
$this->cache = $this->calc();
$this->needCalc = false;
}
return $this->cache;
}
private function calc() {
return $this->a + $this->b;
}
public function __sleep() {
// $this->a と $this->b だけをシリアライズしたい
}
public function __wakeup() {
// シリアライズしなかったものの初期値
$this->needCalc = true;
$this->cache = null;
}
}
// インスタンス化およびキャッシング
$obj = new Klass(42, 23);
$obj->getResult();
// シリアライズ不要なフィールドは捨てられたか?
// シリアライズしなかったフィールドに
// 正しく初期値が与えられているか?
$newObj->getResult();
PD9waHAKCmNsYXNzIEtsYXNzIHsKICAvLyDooqvmvJTnrpflrZDvvIjjgrfjg6rjgqLjg6njgqTjgrrjgZnjgovvvIkKICBwcml2YXRlICRhOwogIC8vIOiiq+a8lOeul+WtkO+8iOOCt+ODquOCouODqeOCpOOCuuOBmeOCi++8iQogIHByaXZhdGUgJGI7CgogIC8vIOWGjeioiOeul+OBjOW/heimgeOBi+OBqeOBhuOBi+OCkuihqOOBme+8iOOCt+ODquOCouODqeOCpOOCuuOBl+OBn+OBj+OBquOBhO+8iQogIHByaXZhdGUgJG5lZWRDYWxjOwogIC8vIOioiOeul+e1kOaenO+8iOOCt+ODquOCouODqeOCpOOCuuOBl+OBn+OBj+OBquOBhO+8iQogIHByaXZhdGUgJGNhY2hlOwoKICBwdWJsaWMgZnVuY3Rpb24gX19jb25zdHJ1Y3QoJGEsICRiKSB7CiAgICAkdGhpcy0+YSA9ICRhOwogICAgJHRoaXMtPmIgPSAkYjsKICAgICR0aGlzLT5uZWVkQ2FsYyA9IHRydWU7CiAgICAkdGhpcy0+Y2FjaGUgPSBudWxsOwogIH0KCiAgcHVibGljIGZ1bmN0aW9uIGdldFJlc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