Creating the Singleton design pattern in PHP5

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

How would one create a Singleton class using PHP5 classes?

21条回答
  •  庸人自扰
    2020-11-22 04:59

    The Real One and Modern way to make Singleton Pattern is:

    So now you can use it like.

    label = $label;
      }
    
      public function getLabel()
      {
        return $this->label;
      }
    
    }
    
    // create first instance
    $database = Database::instance();
    $database->setLabel('Abraham');
    echo $database->getLabel() . PHP_EOL;
    
    // now try to create other instance as well
    $other_db = Database::instance();
    echo $other_db->getLabel() . PHP_EOL; // Abraham
    
    $other_db->setLabel('Priler');
    echo $database->getLabel() . PHP_EOL; // Priler
    echo $other_db->getLabel() . PHP_EOL; // Priler
    

    As you see this realization is lot more flexible.

提交回复
热议问题