Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does static variables in php persist across the requests?

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?

like image 464
Vaibhav Kamble Avatar asked Feb 06 '09 12:02

Vaibhav Kamble


People also ask

Are static variables persistent?

A static variable will persist its value throughout the lifetime of the process and only one will exist per class, not instance.

Do static variables stay the same?

Since the static variables stay the same throughout the life cycle of the program, they are easy to deal with for the memory system and they are allocated in a fixed block of memory. Here is an example of static variables with different duration. All the static variables persist until program terminates.

How do static variables work in PHP?

The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.

Can static variables be changed in PHP?

No. Static can be used to declare class variables or within function to declare a variable which persists over function calls, but not over executions of the script.


2 Answers

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>'; 
like image 99
Ross Avatar answered Oct 13 '22 20:10

Ross


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

like image 42
Matt Razza Avatar answered Oct 13 '22 19:10

Matt Razza