You cannot share variables across requests - they would need to be either send via a POST
or GET
request.
Behavior of static property in PHP
-
02-07-2022 - |
سؤال
I'm trying to understand how static property works.My example:
class Model_Cart{
static public $_a;
}
I created object of this class in different scripts. Script 1:
Model_Cart::$_a = true;
var_dump(Model_Cart::$_a);
Output is "true".
But if I execute second script after:
var_dump(Model_Cart::$_a)
Output is NULL.
I expected that static variable is shared beetwen all instance of class. Can you explain this behaviour?
المحلول 2
نصائح أخرى
The behaviour is as expected actually. Please take note that you cannot - without the use of sessions, cookies or a database of some sort - share properties or values between requests. That's because http is a so called 'stateless protocol', which pretty much means that with every request the application is build up again from the ground up.
Please take a note at the following examples:
script_number_one.php
$my_var = 'hello world!';
echo $my_var; // does what you think it does
script_number_two.php
echo $my_var; // echoes nothing, or raises a warning that the var doesn't exist
As you can see it doesn't matter what you do in script one, as script two just doesn't know about no 1 (and doesn't care either actually).
Pretty much the same happens with your class. But you can do something else though, and this is probably what you did expect:
class myStaticClass {
public static $static_var = 'Hello world!';
public function alter_static_value($new_value) {
self::$static_var = $new_value;
}
}
$_obj_1 = new myStaticClass;
$_obj_2 = new myStaticClass;
echo $_obj_1::$static_var; // echoes 'Hello World!'
echo $_obj_2::$static_var; // also echoes 'Hello world!'
$_obj_1->alter_static_value('Bye world!');
echo $_obj_2::$static_var; // echoes 'Bye world!';
As you can see, a static value isn't particular for an object instance, but is specific for the whole class, and thus accessible for all objects that instantiated that particular class.
Hope this helps.