I have one php function on a seperate php file and I am calling this function from another php file by using an jquery ajax call. The php function is just increment its static value by 1 but its not incremented as I see the output. The static variable doesnt behave as I think.
Whats the reason for that ?
Thanks in advance,
Simple function:
function IncrementByOne()
{
static $count = 0;
$count++;
echo $count;
}
Static function variables are persistent across function calls of the same request. They don't keep their value across multiple requests.
Actually, that is true of all PHP variables, apart from the magic $_SESSION variable: They are always reset after the current request ends.
If you want a variable to persist between multiple requests, you can put it into:
a session
a database
a flatfile
APC
memcached
...
Related
My website (served by PHP) uses some values, which are expensive to calculate (and the calculation is deterministic), therefore I'd like to cache the result at the first request. Then I could use this function:
function MyValue($valueID) {
if (!isset($myValueCache[$valueID])) {
$myValueCache[$valueID] = ... // The long and expensive calculation.
}
return $myValueCache[$valueID];
}
The question is, how to declare $myValueCache to preserve its value between different calls of the script? I'd call it "server-level static variable" or something like. A simple static variable is not the desired solution. http://www.elated.com/articles/php-variable-scope-all-you-need-to-know/ writes: "Once the script exits, a static variable gets destroyed, just like local and global variables do." I'd like to preserve the value until I explicitly unset it. Thanks :)
PS. "expensive" means database access for example. Calculating and hard-coding the result is not possible at development time.
You should consider using of any in-memory database, like Redis or Memcached. You can also try to cache values in files, but it will be slower than in-memory databases.
I met storage problem with php.
What I want is when each time I visit the function Main of Class A, I can get the value of variable $temp of last time.
P.s. I know I can use session, but it wastes many memory, and not safe.
so I want to find another solution.
Below is the code.
class A {
//initilize the value, how to make it just initialize once?
private static $temp = 0;
public function Main() {
echo "Last time I was=". $this->temp;
$this->temp += 1;
}
}
Thank you for your guys' help! Waiting for your idea
static variable value is stored in a request lifetime.sessions are safe enough to even store authentication data in it so if you want to store this data between multiple requests i recommend sessions or database.
Will it be useful if you store it in a separate file, you overwrite the value in it and read from it when needed?
This may not be the best solution to my problem, but I'm interested to know anyway.
Is it possible to defer a function or piece of code till after a while loop ends? I assumed this happened anyway if it was placed below, but that doesn't seem to be the case.
What I'm trying to accomplish is inside the while loop some session data is being saved (if it does not exist, which is the condition). When the loop finally ends, since the session data is set, the code below which relies on the session data can be executed.
This is in a CodeIgniter 3.0 system, so it is using the session driver:
// Uses a helper function session_isset (see below) to check if the session data is set, and if at least one of the supplied data variables is null then try to set it
while(!session_isset(array('instance_id','instance_prefix'))) {
$this->session->set_userdata('instance_id', $instance->instance_id);
$this->session->set_userdata('instance_prefix', $instance->instance_prefix);
}
// The get_managers() function, which ultimately calls a model function, relies on the set session data to get a table prefix which is prepended to all relevant database queries
// This should ideally only be allowed to run once the session data has been confirmed as set
if($manager = $this->manager->get_managers(array($manager_id))[0]) {
$manager->instance_id = $instance->instance_id;
$manager->instance_prefix = $instance->instance_prefix;
echo json_encode($manager);
}
function session_isset($data) {
$ci =& get_instance();
foreach ($data as $value) {
if(is_null($ci->session->userdata($value))) return FALSE;
}
return TRUE;
}
So just to reiterate, is there a way to defer code until a while loop has ended, similar to a callback?
Also, is there perhaps a better way to ensure session data is set before running functions that depend on it?
If I run the following PHP code, I get 123. I don't understand the logic behind it. What I think is when I call the function each time it suppose to output 1. So the output should be like 111.
function keep_track() {
STATIC $count = 0;
$count++;
print $count;
}
keep_track();
keep_track();
keep_track();
// output 123
I know that a static variable holds the value even after the function exits but in the above function I am assigning a value in the very first line, yet it still adding +1 with the previous value of $count.
Could you please explain this? (I am sorry if I sound like a stupid.. but I am trying to find out how exactly this happening)
$count is initialized only in first call of function and every time the method is called, it increments $count.
In this link, scroll down to Using static variables for a better understanding.
The code static $count = 0; is executed once upon compilation which is why with each call of your function the value is not overwritten. See the note "Static declarations are resolved in compile-time." at http://www.php.net/manual/en/language.variables.scope.php
I have a flash application which uses a single php file to retrieve records from a database (using the Zend framework). When the application first begins, I make a call to the php to set a class variable, so that all future requests to the database will use this variable to select records based on its value. So here is how the class begins:
class MyClass
{
private $animal = "";
public function setAnimal($anim) {
$this->animal = $anim;
echo($this->animal); //this correctly prints the variable I passed in
}
Later, based on user input, I make a call to a different method in this class, but it's as if the class variable $animal has been forgotten, because it no longer has a value on any subsequent accessing of the class:
public function getAnimals()
{
echo('getAnimals: ');
echo($this->animal); //this prints nothing - as if it doesn't know what "animal" is
$result = mysql_query("SELECT * FROM animals WHERE animal='$this->animal'"); //and therefore this query doesn't work
$t = array();
while($row = mysql_fetch_assoc($result))
{
array_push($t, $row);
}
return $t;
}
So my question is, how can I get a PHP class variable to persist so that I can set it once, and I can access it anytime during the life of an application?
I could be mis-interpreting your question, but it sounds like you first make a call to a PHP script from your Flash, and later you are making a second call to the PHP script from the Flash and expecting a certain variable to be set?
If this is the case, then it is also the problem. PHP is stateless. Every time you access a PHP script (ie, request the URL), the PHP environment is re-created from scratch. As soon as the request is done and the PHP script is finished executing, the environment is destroyed (ie. the web server thread shuts down, and the PHP environment is lost). Anything you set or do in your first request won't exist on your second request.
If you want information to persist, you can use sessions or cookies. Since you're using Flash, sessions is probably the best way to go. The first time you call your script, generate a session token and pass it back to the flash with your response. On all subsequent calls, your Flash should provide the session token, and you can store/fetch any state variables you need from $_SESSION.