<?php
class
LRU_Cache
{
private
$array_lru
=
array
();
private
$max_size
= 0;
function
__construct(
$size
)
{
$this
->max_size =
$size
;
}
public
function
set_value(
$key
,
$value
)
{
if
(
array_key_exists
(
$key
,
$this
->array_lru)) {
unset(
$this
->array_lru[
$key
]);
}
if
(
count
(
$this
->array_lru) >
$this
->max_size) {
array_shift
(
$this
->array_lru);
}
$this
->array_lru[
$key
] =
$value
;
}
public
function
get_value(
$key
)
{
$ret_value
= false;
if
(
array_key_exists
(
$key
,
$this
->array_lru)) {
$ret_value
=
$this
->array_lru[
$key
];
unset(
$this
->array_lru[
$key
]);
$this
->array_lru[
$key
] =
$ret_value
;
}
return
$ret_value
;
}
public
function
vardump_cache()
{
echo
"<br>"
;
var_dump(
$this
->array_lru);
}
}
$cache
=
new
LRU_Cache(5);
$cache
->set_value(
"01"
,
"01"
);
$cache
->set_value(
"02"
,
"02"
);
$cache
->set_value(
"03"
,
"03"
);
$cache
->set_value(
"04"
,
"04"
);
$cache
->set_value(
"05"
,
"05"
);
$cache
->vardump_cache();
echo
"<br>"
;
$cache
->set_value(
"06"
,
"06"
);
$cache
->vardump_cache();
echo
"<br>"
;
$cache
->set_value(
"03"
,
"03"
);
$cache
->vardump_cache();
echo
"<br>"
;
$cache
->set_value(
"07"
,
"07"
);
$cache
->vardump_cache();
echo
"<br>"
;
$cache
->set_value(
"01"
,
"01"
);
$cache
->vardump_cache();
echo
"<br>"
;
$cache
->get_value(
"04"
);
$cache
->vardump_cache();
echo
"<br>"
;
$cache
->get_value(
"05"
);
$cache
->vardump_cache();
echo
"<br>"
;
$cache
->get_value(
"10"
);
$cache
->vardump_cache();
echo
"<br>"
;