PHP 8.5.0 Beta 1 available for testing

Memcache::get

memcache_get

(PECL memcache >= 0.2.0)

Memcache::get -- memcache_getИзвлекает элемент с сервера

Описание

Memcache::get(string $key, int &$flags = ?): string
Memcache::get(array $keys, array &$flags = ?): array
memcache_get(Memcache $memcache, string $key, int &$flags = ?): string
memcache_get(Memcache $memcache, array $keys, array &$flags = ?): array

Метод Memcache::get() возвращает данные элемента с ключом key, если сервер содержит такой ключ.

При передаче в метод Memcache::get() массива ключей возвращается массив значений. В массив с результатами добавляются только те пары «ключ — значение», которые содержит кеш сервера, остальные игнорируются.

Список параметров

key

Ключ или массив ключей для извлечения элементов.

flags

При вызове метода с этим аргументом параметр заполняется флагами, которые метод извлёк вместе со значениями. Это в точности те флаги, которые указывают, например, при вызове метода Memcache::set(). Младший байт каждого целочисленного значения резервируется для внутренних целей модуля pecl/memcache, например, чтобы указать статус сжатия или сериализации.

Возвращаемые значения

Метод возвращает значение, которое связали с ключом key, или массив найденных пар «ключ — значение», если в параметр key передали массив. Метод возвращает значение false, если возникла ошибка, сервер не нашёл ключ key или с ключом key связали пустой массив.

Примеры

Пример #1 Пример извлечения записи кеша методом Memcache::get()

<?php

/* Процедурный API */
$memcache_obj = memcache_connect('memcache_host', 11211);
$var = memcache_get($memcache_obj, 'some_key');

/* Объектно-ориентированный API */
$memcache_obj = new Memcache();
$memcache_obj->connect('memcache_host', 11211);
$var = $memcache_obj->get('some_key');

/*
Параметр также принимает массив ключей.
В массив с результатами добавляются только те элементы,
которые содержит кеш сервера, остальные игнорируются
*/

/* Процедурный API */
$memcache_obj = memcache_connect('memcache_host', 11211);
$var = memcache_get($memcache_obj, Array('some_key', 'another_key'));

/* Объектно-ориентированный API */
$memcache_obj = new Memcache();
$memcache_obj->connect('memcache_host', 11211);
$var = $memcache_obj->get(array('some_key', 'second_key'));

?>

Добавить

Примечания пользователей 7 notes

up
12
clover at fromru dot com
12 years ago
$flags stays untouched if $key was not found on the server, it's helpfull to determine if bool(false) was stored:

<?php

$memcache
= new Memcache();

$memcache->set('test', false); //
$flags = false;
var_dump($memcache->get('test', $flags)); // bool(false)
var_dump($flags); // int(256) - changed to int

$memcache->delete('test');

$flags = false;
var_dump($memcache->get('test', $flags)); // bool(false)
var_dump($flags); // bool(false) - untouched

?>
up
6
Michael Brenden
14 years ago
Beware, if there's a backslash present in the key name then the results are unpredictable and random.

I was generating keys like this:

$mc_key = get_called_class(). $_COOKIE['crumb'];

This works fine when get_called_class() returns CLASSNAME.

But then I began using namespaces, and get_class_class() of course returned NAMESPACE\CLASSNAME

Well that backslash sends Memcache into quite the tizzy.
No errors, mind you, just insanity.
up
4
bijay dot rungta at gmail dot com
12 years ago
Note that if you include spaces in your keys when saving Data and use array of keys to get the Data, The returned array will replace spaces with underscores in the keys.

<?php

$memcache
= new Memcache;
$memcache->connect('localhost');
$memcache->set('my-key', 'value1', 0, 300);
$memcache->set('key with space', 'value 2', 0, 300);

print_r($memcache->get(array('my-key', 'key with space'))); // Array ( [my-key] => value1 [key_with_space] => value 2 )

?>

Memcache replaces spaces with underscores when saving, it does so when doing a get too, but when you do a get with single key (string) you don't notice this as it merely returns the value. But when you do a get for array of keys, you would expect the same keys in the returned array but it replaces spaces by underscores in them.
up
1
csongor at halmai dot hu
10 years ago
Avoid reading too many values from memcahce. Each get() consumes some memory. You should cache the values instead, once they are read. Illustration of bad practice:

<?php // reading from memcache leaks

$m = new Memcache();
$m -> connect( "localhost", "11211" );
$m -> add("foo", "bar");

for(;;) {
// this "endless" loop will finish because it eats up all the memory
$res = $m -> get("foo");
print
memory_get_usage()."\n"; // this writes bigger and bigger numbers
}
up
0
jakub dot lopuszanski at nasza-klasa dot pl
17 years ago
If deserialization fails for some reason, that is when memcache server returned flag 1 set, but the value was not a correctly serialized PHP data,
then Memcache::get acts in a following way:

If it was called with a single key to retrieve, then a warning is raised, but since it was not actually a bug of a server, the warning says something confusing like "Memcached Server Error: null" and the function returns bool(false).

If it was called by passing an array (even with a single element in it), then the warning is not raised and the resulting array contains a value bool(false).

Since there are some buffer overrun bugs present in Memcached Server, which from time to time cause overwriting of [part of] data and therefore rendering it impossible to deserialize, make sure to check if the result of Memcache::get contains only string, or deserialized structure. If the result is bool,dobule or long, then something went wrong.
up
-2
a dot karabiowski at gmx dot net
11 years ago
Signature is not correct.

<?php
$memcache
= new Memcache();
$memcache->connect('localhost', 11211);
class
Test { public $property = "testvalue"; }
$test = new Test();
$memcache->set("asdf", $test);
var_dump($memcache->get("asdf"));
/* will return the object, not the string:
class Test#3 (1) {
public $property =>
string(9) "testvalue"
}
*/
?>
up
-2
nate
16 years ago
Be aware that when using the multi-key version, Memcache::get returns bool false if no servers are configured for the pool (and possibly if other errors occur as well while attempting to fetch). Also, Memcache class throws annoying warnings on every get/set/delete-type calls if you have no servers added to the pool.

The following snippet var_dump's bool false, not an empty array like you might expect.

<?php
$cache
= new Memcache;

// no $cache->addServer calls (for example,
due to temporarily disabling use of cache)

// use @ symbol to ignore warning

var_dump(
@
$cache->get(array('one', 'two'))
);
?>
To Top