Shaun
Shaun

Reputation: 4799

PHP global variable loses value during web request

I have a utility class with a static function that utilizes a global variable:

private static function isRateLimited($ip) {
    global $memcached_node;

    $memcache = new Memcache;
    $memcache->connect($memcached_node['host'], $memcached_node['port']) or die ("memcache failure");

    // do stuff
}

The global variable is set up via a chef cookbook. Everything has been working well within the application until a recent change. The change tweaked code execution so that isRateLimited() is called twice during a single web request.

Debugging has revealed that, the first time isRateLimited() is called, the global variable is set and everything work as expected. However, the second time isRateLimited() is called, the global variable returns an empty value (as tested with empty()). The result is that the second connection to memcached fails.

The global is not overwritten or unset anywhere else in the code. Why does the global variable lose its value between executions of the function in the same web request?

For reference, I tried referring to the global using $memcached_node = $GLOBALS["memcached_node"]; as one of my "last ditch effort" darts. The behavior was the same.

Environment

Upvotes: 0

Views: 1449

Answers (2)

Kiril Belah
Kiril Belah

Reputation: 193

Had the similar problem, before static function call global variable exists, inside static function it is empty. It is becoming empty on global keyword. But I was loading code via bootstrap for PHPunit. Without PHPunit it worked as expected.

What I ended up doing is to explicitly assigning variable as super global:

$GLOBALS['foo'] = $foo;

Upvotes: 0

FtDRbwLXw6
FtDRbwLXw6

Reputation: 28889

private static function isRateLimited($ip) {
    var_dump(debug_backtrace()); // or log to file - whatever suits the context
    // ...
}

You can trace the call with PHP's debug_backtrace() function (more info here). Alternatively, you can increment a global counter variable and only do this for the nth call to isRateLimited() for a given server request if you know definitively which call is erroneous.

Upvotes: 1

Related Questions