开发者

Same variable for everyone php?

I was wondering, is there a way to have a sort of variable that would be 'static' meaning that it would be the same for all users in php ? I know that there is a possibility to have a static variable within a function in php but that is not what I want.

I would like everyone to share an object which I would manipulate depending on the user's demand. Or, another开发者_开发百科 example that is similar to what I want is, is there a way to keep a variable that counts the number of visitors (without using any sort of file or database manipulation). That variable would be incremented every time a user come to my page.

Cheers !


Without using a file or database, I believe you could do this using something like APC.

$var = 1;
$key = 'myVariable';
apc_store($key, $var);
echo apc_fetch($key); // 1

If you want to increment it, you can use apc_inc()

echo apc_inc($key); // 2

However, this variable won't be preserved if the cache is cleared (which happens when it fills up or the server is restarted).


Check out semaphores and shared memory and how they work in PHP. With a shared memory variable different processes (users) can use the same memory space and use the same variables. Here's a link to the PHP documentation to get you started:

http://www.php.net/manual/en/function.shm-get-var.php


No. In some (most?) setups, each request is handled in separate processes which don't even share address space with each other. You need a database or other persistent storage mechanism.


I think what you're looking for is a called a global variable.

In reference to page-view counters, we usually do that with variables inside of files. Here's a good example.

You could also do it via database, but if you don't have a database already, it seems like overkill just to get one for a hit counter.


I supposed you could use an Apache server variable. Presumably non-Apache servers would have something similar.

The vars can be set/get with apache_setenv/apache_getenv. The question is whether those would propagate across all apache children, or just the on the PHP script happens to be running under.

Of course, since they're dynamically set, you'd lose the values whenever Apache gets reset.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜