Scope of Static Members in PHP and Concurrency - php

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!

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)

When do PHP objects die?

I'm getting started with objects in PHP and I was wondering when they get deleted. Is it when the PHP file gets finished loading or when it's finished with the function I'm calling? is there anyway to keep the object alive so it can be called in another instance when the file is loaded.
There's a distinction to be made between objects dying and objects being out of scope.
If you are concerned with the logistics of memory management and garbage collection in PHP then as T.J. Crowder pointed out you could read the manual on garbage collection in PHP.
If on the other hand you are more concerned with variable scope, then the answer is that the scope of variables is typically bounded to the block they are declared in. But you can also create global variables, and access them using the global keyword inside of functions - although global variables are generally a bad idea. See the manual for details.
And as far as persisting variables beyond a script, this can only be accomplished via some sort of storage mechanism. In the context of web applications, that is usually accomplished using session state but be careful that the nuances of persisting objects from one session to the next (i.e. one invocation of a script to the next) may be different depending on whether the session state is stored in-process, or out of process. In case it's the latter then the objects will be serialized and deserialzed which makes things a little more complicated.
PHP memory vars is garbage collected, usually they are being removed (decrease ref) when request ends, function out of scope .. etc.
you still can go with singleton pattern, and load only not loaded objects
note that this only works for each single request, if you want to keep the object in memory for more than one request, that's wont work for php,
/**
* Singleton class
*
*/
final class UserFactory
{
/**
* Call this method to get singleton
*
* #return UserFactory
*/
public static function Instance()
{
static $inst = null;
if ($inst === null) {
$inst = new UserFactory();
}
return $inst;
}
/**
* Private ctor so nobody else can instance it
*
*/
private function __construct()
{
}
}
To use:
$fact = UserFactory::Instance();
$fact2 = UserFactory::Instance();
$fact == $fact2;
code example taken from https://stackoverflow.com/a/203359/1291995

Every client request is a new instance of the class?

I wrote a class that builds some url in a page every time there is a client request to the server. In a hypothetical scenario in which 100 clients, at the same time, require a server connection, it should produce 100 instances of that class, right?
So I would like to know what would be the result of many instances at the same time on the page and if this is a good practice to solve my problem with the "url generator".
Thanks
[EDIT]
What I tried to do it was to use __set() method and overloading to build the URLs. The fact is that I started to study object-oriented programming in php and I wanted to try a practical application of this method. Here is a piece of code:
Class BuildPath {
private $ServerPath;
private $ServerUrl;
private $UrlPath;
private $data;
function __construct()
{
$this->ServerPath = $_SERVER['DOCUMENT_ROOT'];
$this->ServerUrl = $_SERVER['HTTP_HOST'];
$this->UrlPath = $_SERVER['REQUEST_URI'];
$this->data = array();
}
public function __get($key) {
return $this->$key;
}
public function __set($key,$value)
{
$this->data[$key] = $value;
}
// others methods
After reading some of the comments I think you are misunderstanding what PHP is and isn't. Each time a user makes a request to the page it is "creating an instance" as you say. After the page is loaded the "instance" is removed. This is how PHP works.
Singleton classes will not share data with one users instance with another users instance but instead share that users intsance of that class with that same users instance of another class.
This is how PHP operates and is normal. Since php doesn't "store" data between each request this is where memcache or mysql come into use or sessions.
One thing to be aware of is that PHP has no application scope, meaning that there is no shared memory between requests. A database (mysql) or in memory store (memcache) is typically used to share the state of objects between requests.
Without knowing more specifics to your question, in general, each request made to the webserver will spawn a new instance of your class, but each class will only be aware of it's own state unless you have a mechanism to share it.

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