Creating the Singleton design pattern in PHP5

前端 未结 21 1740
猫巷女王i
猫巷女王i 2020-11-22 04:21

How would one create a Singleton class using PHP5 classes?

21条回答
  •  有刺的猬
    2020-11-22 04:54

    You probably should add a private __clone() method to disallow cloning of an instance.

    private function __clone() {}
    

    If you don't include this method the following gets possible

    $inst1=UserFactory::Instance(); // to stick with the example provided above
    $inst2=clone $inst1;
    

    now $inst1 !== $inst2 - they are not the same instance any more.

提交回复
热议问题