Creating the Singleton design pattern in PHP5

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

How would one create a Singleton class using PHP5 classes?

21条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 05:05

    Here's my example that provides ability to call as $var = new Singleton() and also creating 3 variables to test if it creates new object:

    class Singleton{
    
        private static $data;
    
        function __construct(){
            if ($this::$data == null){
                $this->makeSingleton();
            }
            echo "
    ".$this::$data; } private function makeSingleton(){ $this::$data = rand(0, 100); } public function change($new_val){ $this::$data = $new_val; } public function printme(){ echo "
    ".$this::$data; } } $a = new Singleton(); $b = new Singleton(); $c = new Singleton(); $a->change(-2); $a->printme(); $b->printme(); $d = new Singleton(); $d->printme();

提交回复
热议问题