I make this observation: memcache PHP // why this???

I make this observation: // why this???
echomc(); // this give error … if commented and uncomment next line Not error
//echo memcache_get($memcache_obj, ‘var_key’);

Warning: memcache_get() expects parameter 1 to be MemcachePool, null given in /var/sites/b/xyz.com/public_html/xyz.php on line 45

[php]/* procedural API */

/* connect to memcached server */
$memcache_obj = memcache_connect(‘x.y.z.f’, 11211);

/*
set value of item with key ‘var_key’
using 0 as flag value, compression is not used
expire time is 30 seconds
*/

memcache_set($memcache_obj, ‘var_key’, ‘some variable’, 0, 30);

function echomc() {
echo memcache_get($memcache_obj, ‘var_key’); // line 45
}

echomc(); // this give error … if commented and uncomment next line Not error
//echo memcache_get($memcache_obj, ‘var_key’);[/php]

You cannot access arbitrary variables from within a function. If you want to use the Memcached connection in the function, pass it to a parameter:

The function declaration
[php]function echo_memcache_value($connection, $key)
{
echo memcache_get($connection, $key);
}
[/php]

The function call
[php]<?php

echo_memcache_value($memcache_obj, ‘var_key’);
[/php]

For the record: It’s theoretically possible to import global variables with the [tt]global[/tt] keyword, but this is confusing and should be avoided at all cost. Use parameters.

[php] $memcache_obj = memcache_connect(‘x.y.z.f’, 11211);
[/php]

OK, btw this^ can called inside each function, otherwise, but also to point to same memcache?

Not sure if I understand your question. You want to call [tt]memcache_connect()[/tt] in the function? This would be extremely inefficient, because you’d establish a new connection on each function call. It’s also unnecessary code duplication. So, no, that’s not an option.

What’s wrong with parameters?

yes that mean

if have
set

get

delete

call inside each - at least for debugging or testing server is OK? - >>>
[php]$memcache_obj = memcache_connect(‘x.y.z.f’, 11211);

memcache_set($memcache_obj, ‘var_key’, ‘some variable’, 0, 30);

function echomc() {
$memcache_obj = memcache_connect(‘x.y.z.f’, 11211);
echo memcache_get($memcache_obj, ‘var_key’); // line 45
}[/php]

Why would you do that? This makes absolutely no sense to me.

At least in testing server is OK…?

Again: What you’re doing makes no sense to me, neither in production nor for testing nor for anything else.

If you insist on doing it, go ahead. I can’t stop you. But I won’t tell you that it’s OK, because I see no reason to make that statement.

if in production using apc cache and in development memcache - I want not modify first functions - just create fwd…functions…

Sponsor our Newsletter | Privacy Policy | Terms of Service