Skip to content

Instantly share code, notes, and snippets.

@sarelvdwalt
Last active August 29, 2015 13:57
Show Gist options
  • Save sarelvdwalt/9396481 to your computer and use it in GitHub Desktop.
Save sarelvdwalt/9396481 to your computer and use it in GitHub Desktop.
Demonstrates how to have a static cache variable (array) which is capped to a maximum count of entries, with last-in-first-out.
<?php
/**
* Demonstrate how to have a static cache variable that is capped to a maximum count.
*
* User: sarel
* Date: 2014/03/06
* Time: 8:27 PM
*/
class testShifting {
public static $cache = array();
const CACHE_MAX = 5;
public function calculateSomething () {
if (count(self::$cache) >= self::CACHE_MAX) {
array_shift(self::$cache);
}
self::$cache[] = date('Y-m-d H:i:s');
}
}
$bleh = new testShifting();
for ($i = 0; $i < 7; $i++) {
$bleh->calculateSomething();
print_r(testShifting::$cache);
sleep(1);
}
@sarelvdwalt
Copy link
Author

The cap is 5, so we only always want 5 entries in the array, this will thus yield:

Array
(
    [0] => 2014-03-06 20:35:57
)
Array
(
    [0] => 2014-03-06 20:35:57
    [1] => 2014-03-06 20:35:58
)
Array
(
    [0] => 2014-03-06 20:35:57
    [1] => 2014-03-06 20:35:58
    [2] => 2014-03-06 20:35:59
)
Array
(
    [0] => 2014-03-06 20:35:57
    [1] => 2014-03-06 20:35:58
    [2] => 2014-03-06 20:35:59
    [3] => 2014-03-06 20:36:00
)
Array
(
    [0] => 2014-03-06 20:35:57
    [1] => 2014-03-06 20:35:58
    [2] => 2014-03-06 20:35:59
    [3] => 2014-03-06 20:36:00
    [4] => 2014-03-06 20:36:01
)
Array
(
    [0] => 2014-03-06 20:35:58
    [1] => 2014-03-06 20:35:59
    [2] => 2014-03-06 20:36:00
    [3] => 2014-03-06 20:36:01
    [4] => 2014-03-06 20:36:02
)
Array
(
    [0] => 2014-03-06 20:35:59
    [1] => 2014-03-06 20:36:00
    [2] => 2014-03-06 20:36:01
    [3] => 2014-03-06 20:36:02
    [4] => 2014-03-06 20:36:03
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment