Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are static class variables shared?

Tags:

oop

php

static

My understanding of PHP static class variables in a Wordpress environment is that, if 2 or more objects of the same class are instantiated within the same http request, then their class static variables will be shared.

What about different http requests? Are class static variables ever shared between http requests? Or is a completely new copy of the object created for each http request?

like image 381
flymike Avatar asked Feb 10 '23 11:02

flymike


2 Answers

No, they are not shared. On each request completely new object is being created. Keep in mind that HTTP is stateless protocol. And that's the reason why many people consider Singleton as anti-pattern (1).

So, basically if you have the following code:

<?php

class MyClass {

    public function __construct() {
        // any action
    }

    public function anyMethod() {
        // any code
    }

}

$obj = new MyClass;

$obj is created from the scratch for each request. Actually, that's not everything. Your whole application is "created" from the scratch.


1) Why is Singleton considered an anti-pattern?

like image 70
Kristian Vitozev Avatar answered Feb 12 '23 02:02

Kristian Vitozev


TL;DR : No. Static/global state does not persist between http requests.


You need to understand the difference between a class and an object to answer your question.

A class is the template from which individual objects are create. A class in itself is static, meaning that it has a global scope. Once you've declared a class, you can do new Class from anywhere in your code in the current process.

An object is an instance of a class. It can only be accessed through the variable (pointer) containing it.

Now what the static keyword means? Basically, when you declare a static property, you declare a property for the Class. As I said before, a class is unique and global so its properties will also be uniques and globals.

class Exemple
{
    public static $foo = 42;
}

echo Exemple::$foo; // 42

$object = new Exemple;
$object2 = new Exemple;
echo $object::$foo; // 42
echo $object2::$foo; // 42

Exemple::$foo = 1;
echo Exemple::$foo; // 1
echo $object::$foo; // 1
echo $object2::$foo; // 1

On the other hand, when you declare an object property, it will only be accessible through an object and the value it contains will be specific to that object.

class Exemple2
{
    public $bar;
}

$object = new Exemple2;
$object2 = new Exemple2;
$object->bar = 42;

echo $object->bar; // 42
echo $object2->bar; // null

Now that we've clarified the static thing, we can talk about http requests.

Everytime your web server receives a new request, it starts a new PHP process that will execute the specified script. Hence, global state will not persist between http requests because each request is executed in its own PHP process.

like image 44
Alfwed Avatar answered Feb 12 '23 04:02

Alfwed