すべてのサブクラスとアクセサー関数private static
のキャッシュ データを保持する変数の組み合わせは機能するように聞こえますが、それほど複雑ではありません。protected
class Base {
private static $cache = array();
protected getCacheItem($key) {
$type = get_class($this);
if (!isset(self::$cache[$type])) {
self::$cache[$type] = array();
}
// add checks to taste
return self::$cache[$type][$key];
}
protected function setCacheItem($key, $value) {
// similar to the above
}
}
ここから考えると、キャッシュへのアクセスが非常に便利になるように工夫することができます。
class Base {
private static $cache = array();
// WARNING! QUESTIONABLE PRACTICE: __get returns by reference
// Also, overriding __get ONLY might not lead to an intuitive experience
// As always, documenting non-standard behavior is paramount!
public function &__get($name) {
if ($name != 'cache') {
// error handling
}
$type = get_class($this);
if (!isset(self::$cache[$type])) {
self::$cache[$type] = array();
}
return self::$cache[$type];
}
}
その後、これを次のように使用できます
$b = new Base;
$b->cache['foo'] = 'bar';
実際に見てください。