note 115204 added to language.oop5.overloading
| From: | ortreum | Date: | Thu, 12 Jun 2014 09:31:48 +0000 |
| Subject: | note 115204 added to language.oop5.overloading | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-199662@lists.php.net to get a copy of this message | ||
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();
----
Server IP: 72.52.91.14
Probable Submitter: 87.230.23.85
----
Manual Page -- http://php.net/manual/en/language.oop5.overloading.php
Edit -- https://master.php.net/note/edit/115204
Del: integrated -- https://master.php.net/note/delete/115204/integrated
Del: useless -- https://master.php.net/note/delete/115204/useless
Del: bad code -- https://master.php.net/note/delete/115204/bad+code
Del: spam -- https://master.php.net/note/delete/115204/spam
Del: non-english -- https://master.php.net/note/delete/115204/non-english
Del: in docs -- https://master.php.net/note/delete/115204/in+docs
Del: other reasons-- https://master.php.net/note/delete/115204
Reject -- https://master.php.net/note/reject/115204
Search -- https://master.php.net/manage/user-notes.php