Singleton pattern ensures that a class has only one instance and provides a global access point. It ensures that only one object is available and under control in the application. The Singleton pattern provides a way to access its unique object directly without instantiating the object of the class.
<?php class database { public static $connection; private function __construct(){ echo "connection created"; } public function connect(){ if(!isset(self::$connection)){ self::$connection = new database(); } return self::$connection; } } $db = database::connect(); $db2 = database::connect(); ?>
connection created
In the above example, we follow the singleton pattern, so the object $db2 cannot be created. Only one object is created and is available throughout the application.
The above is the detailed content of In PHP, what is the concept of singleton design pattern?. For more information, please follow other related articles on the PHP Chinese website!