views:

1487

answers:

3

Static variable gotcha in php

I am from Java background and have switched to php for one project recently. I have found one unexpected behaviour in php.

Value set to some static variable is not staying persistent across the requests.

I am not sure if this is the expected bahaviour. Because in java , you can always persist very commonly used variables or say constants like dbname,hostname,username,password across the requests so that you don't have to read them always from local property files.

Is this behaviour normal ? And if it is normal then is there any alternative by which I can persist values assigned to variables across the requests ?

Can someone suggest me a better way of doing this in php?

+2  A: 

No, while a static variable will stay for the current request you'll need to add it to a session to persist it's value across requests.

Example:

session_start();

class Car {
    public static $make;
    public function __construct($make) {
        self::$make = $make;
    }
}

$c = new Car('Bugatti');
echo '<p>' . Car::$make . '</p>';
unset($c);

if (!isset($_SESSION['make'])) {
    echo '<p>' . Car::$make . '</p>';
    $c = new Car('Ferrari');
    echo '<p>' . Car::$make . '</p>';
}

$_SESSION['make'] = Car::$make;

echo '<p>' . $_SESSION['make'] . '</p>';
Ross
Thanks Ross. I am going to store the structure in xml and read it at the start of the session and store it in session and refer it till session ends.
Vaibhav Kamble
A: 

Static variables are only applicable to one single request. If you want data to persist between requests for a specific user only use session variables.

A good starter tut for them is located here: http://www.tizag.com/phpT/phpsessions.php

Mr. Pig
+1  A: 

If you begin working with complex data sets across sessions you may want to look into storing data in objects that get serialized to the database and drawn out on session restore.

Variables in PHP aren't meant to be persistent. The flow of your application (the stack) is executed start to finish on each page run. There is nothing living in the background that continues your logic or application. The closest thing is a session but you do not want to store information like db access etc. in there.

Your database configurations should be in some sort of config or environment file that are accessed one time to connect to the database, once a connection has been made you can simply query whenever needed and use the connection handle to identify what connection to use.

Syntax
The solution you are stating to the problem is having overhead of IO read write operations.It is exactly the problem I was trying to overcome by implementing this solution. I think finally i have to store it in file and read it at the start of session and store that in session.Thanks anyways :)
Vaibhav Kamble
If you are considering IO issues check out memcache: http://us2.php.net/manual/en/intro.memcache.php
Syntax