'static variables in php not holding value
I have written a demo program to describe a problem I'm having with static variables in php. I have a singleton class, History.php, that contains a static $idx variable intially set to -1. An incIdx() function in the History class increments $idx. The demo starts by calling index.php which gets an instance of History, repeatedly calls incIdx() and displays the $idx final value. Then, on clicking a button, test.php is called which gets the History instance, repeatedly calls incIdx(), and displays the final value. What I don't understand is, the value created by index.php is not the starting value for the test.php. That is, index.php and test.php both start with the initial value = -1. The code follows:
<?php
class History {
private static int $idx;
private static $instance = null;
private function __construct() {
$this::$idx = -1;
}
public static function getHistory() {
if (self::$instance === null) {
self::$instance = new History();
}
return self::$instance;
}
public function incIdx() {
$this::$idx++;
}
public function getIdx(): int {
return $this::$idx;
}
}
<?php
require_once "History.php";
$instance = History::getHistory();
for ($i = 0; $i < 5; $i++) {
$instance->incIdx();
}
$value = $instance->getIdx();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Static</title>
</head>
<body>
<h1>In index.php</h1>
<h2>Current idx = "<?php echo $value; ?>"</h2>
<button type="button"><a href="test.php">Click to continue</a></button>
</body>
</html>
<?php
require_once "History.php";
$instance = History::getHistory();
for ($i = 0; $i < 5; $i++) {
$instance->incIdx();
}
$value = $instance->getIdx();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Static</title>
</head>
<body>
<h1>In test.php</h1>
<h2>Current idx = "<?php echo $value; ?>"</h2>
</body>
</html>```
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
