PHP中Singleton类的多个实例

PHP中Singleton类的多个实例,php,web-applications,singleton,Php,Web Applications,Singleton,我有以下PHP中的单例类 class CounterBalance{ private static $instance; private $counterBalance; private function __construct(){ $this->counterBalance = mt_rand(1, 4); } // Getter method for creating/returning the single

我有以下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;
    }

}
在同一个php页面上,它工作正常。但它不能跨页面正常工作。当我在随后的php页面中进行相同的函数调用时,我得到了不止一个CounterBalance实例

谁能解释一下为什么会这样

提前感谢。

欢迎来到无状态的HTTP世界。 单例只能用于单页加载(或者任何其他PHP数据结构)。当php进程消亡时,单例进程也随之消亡。下一次加载页面时,将再次创建单例。单例仅在单个进程的上下文中是活动的。如果您试图在单个脚本执行期间创建它的十个实例,那么您将维护单个实例

如果需要跨页面的数据持久性,则必须实现状态代理。例如,
$\u会话
$\u获取超全局数据或将数据存储在数据库中(例如),然后在后续页面加载时重新检索数据

CounterBalance::getInstance()->getCounterBalanceValue();