Lifetime of a static variable - php

I'm going through a Joomla book, and I came across the following piece of code in the chapter of MVC pattern:
class QuizController extends JController
{
static function &getInstance(/* some PHP code... */)
{
// use a static array to store controller instances
static $instances;
if (!$instances)
{
$instances = array();
}
/* some PHP code... */
// return a reference to the controller
return $instances[$class];
}
}
What is the lifetime of $instances? When is it destroyed?
If it is alive during the lifetime of the request, then declaring $instances static doesn't make sense, because this code will be run once.
If it is alive during user session, how does PHP engine knows this?

If it is alive during the lifetime of the request, then declaring
$instances static doesn't make sense, because this code will be run
once.
Yes, the static variable only exists for the duration of the request. It's a common design pattern to store an object in a static variable if it's expensive to create, or if having multiple copies will cause problems.
It's not necessarily the case that this function only be called once - it will likely be called multiple times, at least on certain pages / for certain modules.

By the looks of the code, the variable lasts until the script is finished being executed.
Because you can't access the variable from outside that function, and there is no unset() call to that variable, it doesn't get destroyed until the end of script execution.

Related

Can I call a static property out of class? [duplicate]

I am looking for assurance that static variables are NOT stored between PHP requests. The following previous questions:
PHP static variables across multiple .php pages
Does static variables in php persist across the requests?
Static variables across sessions
clearly say that they aren't but they are more in the context of providing a way to maintain state rather than a specific discussion of what is the expected behaviour.
As an example, if I have PHP code as follows:
function myfunc()
{
static $a=0;
print $a++;
}
for ($i=0;$i<10;$i++) myfunc();
then I get output of 0123456789 every time I run it. My instinct/understanding of PHP makes me fairly sure that this has to be the case.
In my own experiments, I've shut a (preforking) apache down to one child to make sure that the variable isn't remembered between requests. It isn't remembered between requests as I'd expect. But this is only one scenario in which PHP runs.
What I'm looking for is:
A link to an official piece of documentation that says this is the expected behaviour and won't change. The relevant piece of PHP documentation doesn't mention this explicitly (except in the comments).
Or, an example of when static variables are remembered across requests such as webservers or performance enhancing PHP frameworks out there which will potentially not clear static variables to increase speed between requests.
PHP does not preserve the application state between requests. During an PHP applications life cycle the application is freshly executed with each request. Static variables are meant to preserve the value of a variable in a local function scope when execution leaves the scope. Nowhere in the documentation does it mention that static variables are meant to preserve value across requests.
Yes, you are right, static variables or any variable in PHP except $_SESSION lives only through one request. But you can do it using $_SESSION;
class MyClass
{
public static $a = 0;
public static init()
{
self::$a = isset($_SESSION['a']) ? $_SESSION['a'] : 0;
}
public static printA()
{
self::increaseA();
print(self::$a);
}
public static increaseA()
{
self::$a++;
$_SESSION['a'] = self::$a;
}
}
myClass::init();
for ($i=0;$i<10;$i++) myClass::printA();
The particularity of PHP is that every request reload the whole PHP Code. So, A static method/property get it's default value at each new request.
A confirmation of the fact that the "whole php code is reloaded at every request" is that you can find persistant method like for your database access, in order to avoid making a new connection to your DB for each request (see: mysql_pconnect)

Does PHP variables automatically removed from the memory once move to next page (garbage collection)? [duplicate]

I am looking for assurance that static variables are NOT stored between PHP requests. The following previous questions:
PHP static variables across multiple .php pages
Does static variables in php persist across the requests?
Static variables across sessions
clearly say that they aren't but they are more in the context of providing a way to maintain state rather than a specific discussion of what is the expected behaviour.
As an example, if I have PHP code as follows:
function myfunc()
{
static $a=0;
print $a++;
}
for ($i=0;$i<10;$i++) myfunc();
then I get output of 0123456789 every time I run it. My instinct/understanding of PHP makes me fairly sure that this has to be the case.
In my own experiments, I've shut a (preforking) apache down to one child to make sure that the variable isn't remembered between requests. It isn't remembered between requests as I'd expect. But this is only one scenario in which PHP runs.
What I'm looking for is:
A link to an official piece of documentation that says this is the expected behaviour and won't change. The relevant piece of PHP documentation doesn't mention this explicitly (except in the comments).
Or, an example of when static variables are remembered across requests such as webservers or performance enhancing PHP frameworks out there which will potentially not clear static variables to increase speed between requests.
PHP does not preserve the application state between requests. During an PHP applications life cycle the application is freshly executed with each request. Static variables are meant to preserve the value of a variable in a local function scope when execution leaves the scope. Nowhere in the documentation does it mention that static variables are meant to preserve value across requests.
Yes, you are right, static variables or any variable in PHP except $_SESSION lives only through one request. But you can do it using $_SESSION;
class MyClass
{
public static $a = 0;
public static init()
{
self::$a = isset($_SESSION['a']) ? $_SESSION['a'] : 0;
}
public static printA()
{
self::increaseA();
print(self::$a);
}
public static increaseA()
{
self::$a++;
$_SESSION['a'] = self::$a;
}
}
myClass::init();
for ($i=0;$i<10;$i++) myClass::printA();
The particularity of PHP is that every request reload the whole PHP Code. So, A static method/property get it's default value at each new request.
A confirmation of the fact that the "whole php code is reloaded at every request" is that you can find persistant method like for your database access, in order to avoid making a new connection to your DB for each request (see: mysql_pconnect)

Scope of Static Members in PHP and Concurrency

I have a class that is declared in my application that has a private static member like so:
class SomeClass{
private static myMember = array();
public static getterFunction(){}
public static setterFunction(){}
}
My question / concern is that multiple requests (i'm thinking like a thread in Java) would be able to modify this static member. My understanding of php scope and static members is that they are in the request scope and a new variable is created for each new request and subsequently destroyed after the request has been fulfilled. That said, this would be a difficult thing to test (at least i can't think of an easy way) so i'd rather be safe than sorry.
Is my assessment correct? The PHP docs i've read are pretty crappy in terms of detail so I haven't been able to authoritatively answer yet...
No data, none, is persistent or shared across different instances of PHP scripts unless you explicitly make it so (for example using sessions, databases, files, shared memory). Each PHP instance is its own thing, and each new request causes the webserver to start a separate instance.
So yes, you are correct.
You don't have shared memory by default in PHP. Every single request is being processed in separate process, so they do not know about each other.
I hope I understood your question correctly.
For example:
You have a simple script.php file that sets private field in a class when GET parameter passed:
<?
class A {
private $x = 1;
public function setX($x) {$this->x = $x;}
public function getX() {return $this->x;}
}
$a = new A();
if (!empty($_GET['x'])) {
$a->setX($_GET['x']);
sleep(3);
}
echo $a->getX();
?>
You do two requests at once:
GET /script.php?x=5
GET /script.php
Second request will print you "1". Yes, you are correct!

A new Instances of Singleton Class in PHP for each HTTP request

I have the following Singleton Class in PHP.
class CounterBalance{
private static $instance;
private $counterBalance;
private function __construct(){
$this->counterBalance = mt_rand(1, 4);
}
// Getter method for creating/returning the single instance of this class
public final static function getInstance() {
if(!self::$instance) {
self::$instance = new CounterBalance();
echo "CounterBalance constructed <br/>";
}
return self::$instance;
}
public function getCounterBalanceValue() {
return $this->counterBalance;
}
}
But in the class when I do something like
CounterBalance::getInstance()->getCounterBalanceValue();
on the same php page, it works properly. But it not working properly across pages. I get more than one instance of CounterBalance, when I do the same function call in the subsequent php page.
Can anyone one please explain why this happens.
Thanks in advance.
Welcome to the stateless world of HTTP.
A singleton can only persist for the single page load (or any other PHP data structure, for that matter). When the php process dies, the singleton dies with it. The next time a page is loaded the singleton is created all over again. The singleton is only alive in the context of that single process. If you tried to create ten instances of it during a single script execution you would maintain the single instance.
If you need data persistence across pages you'll have to implement an agent of state. For example, the $_SESSION or $_GET superglobals or store data in a database (for example) and re-retrieve it on subsequent page loads.

Confirmation that PHP static variables do not persist across requests

I am looking for assurance that static variables are NOT stored between PHP requests. The following previous questions:
PHP static variables across multiple .php pages
Does static variables in php persist across the requests?
Static variables across sessions
clearly say that they aren't but they are more in the context of providing a way to maintain state rather than a specific discussion of what is the expected behaviour.
As an example, if I have PHP code as follows:
function myfunc()
{
static $a=0;
print $a++;
}
for ($i=0;$i<10;$i++) myfunc();
then I get output of 0123456789 every time I run it. My instinct/understanding of PHP makes me fairly sure that this has to be the case.
In my own experiments, I've shut a (preforking) apache down to one child to make sure that the variable isn't remembered between requests. It isn't remembered between requests as I'd expect. But this is only one scenario in which PHP runs.
What I'm looking for is:
A link to an official piece of documentation that says this is the expected behaviour and won't change. The relevant piece of PHP documentation doesn't mention this explicitly (except in the comments).
Or, an example of when static variables are remembered across requests such as webservers or performance enhancing PHP frameworks out there which will potentially not clear static variables to increase speed between requests.
PHP does not preserve the application state between requests. During an PHP applications life cycle the application is freshly executed with each request. Static variables are meant to preserve the value of a variable in a local function scope when execution leaves the scope. Nowhere in the documentation does it mention that static variables are meant to preserve value across requests.
Yes, you are right, static variables or any variable in PHP except $_SESSION lives only through one request. But you can do it using $_SESSION;
class MyClass
{
public static $a = 0;
public static init()
{
self::$a = isset($_SESSION['a']) ? $_SESSION['a'] : 0;
}
public static printA()
{
self::increaseA();
print(self::$a);
}
public static increaseA()
{
self::$a++;
$_SESSION['a'] = self::$a;
}
}
myClass::init();
for ($i=0;$i<10;$i++) myClass::printA();
The particularity of PHP is that every request reload the whole PHP Code. So, A static method/property get it's default value at each new request.
A confirmation of the fact that the "whole php code is reloaded at every request" is that you can find persistant method like for your database access, in order to avoid making a new connection to your DB for each request (see: mysql_pconnect)

Categories