note 115204 deleted from language.oop5.overloading by cmb

From: Date: Sun, 18 Dec 2016 09:56:38 +0000
Subject: note 115204 deleted from language.oop5.overloading by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-208648@lists.php.net to get a copy of this message
Note Submitter: ortreum ---- You can use __call and __callStatic for an very simple function based caching approach. If your method result needs to be cached based on its arguments then you only have to add cached_ infront of the name. class thebase { private static $cache = array(); private static function argsAndCache($name, $args) { $hasArray = false; $argsX = $cache = ''; if (count($args) > 0) { foreach ($args as $v) if ($hasArray = (is_array($v) || is_object($v))) break; $argsX = '$args[' . implode('], $args[', array_keys($args)) . ']'; $cache = ($hasArray) ? md5(json_encode($args)) : '[$args[' . implode(']], [$args[', array_keys($args)) . ']]'; } $cache = 'self::$cache[\'' . $name . '\']' . $cache; return array($argsX, $cache); } public function __call($name, $args) { list($argsX, $cache) = self::argsAndCache($name, $args); eval('$result = isset(' . $cache . ') ? ' . $cache . ' : $this->cached_' . $name . '(' . $argsX . ');'); return $result; } public static function __callStatic($name, $args) { list($argsX, $cache) = self::argsAndCache($name, $args); eval('$result = isset(' . $cache . ') ? ' . $cache . ' : ' . get_called_class() . '::cached_' . $name . '(' . $argsX . ');'); return $result; } } class theChild extends thebase { public function cached_abc() { return 1; } public static function cached_s_abc() { return 1; } public static function normal() { return 1; } } $x = new theChild(); echo $x->abc(); echo theChild::s_abc(); echo theChild::normal();

« previous php.notes (#208648) next »