-
- class DatabaseConnection {
- private static $db;
- private static $_handle = null;
-
- public static function get() {
- if ( self::$db == null ){
- echo __LINE__;
- self::$db = new DatabaseConnection();
- }
- return self::$_handle;
- }
-
- private function __construct() {
- $dsn = 'mysql://root:password@localhost/ photos';
- self::$_handle = 123;
- }
-
- }
-
- print( "Handle = ".DatabaseConnection::get()."n" );
- print( "Handle = ".DatabaseConnection::get ()."n" );
- ?>
-
Copy code
9Handle = 123
Handle = 123
[Finished in 0.1s]
Example 2, PHP singleton mode.
-
- class DatabaseConnection
- {
- public static function get()
- {
- static $db = null;//Change the static members of Example 1 into static variables here
- if ( $db == null ){
- echo __LINE__;
- $db = new DatabaseConnection();
- }
- return $db;
- }
-
- private $_handle = null;//This will represent the static removal of Example 1
-
- private function __construct()
- {
- $dsn = 'mysql://root:password@localhost/photos';
- $this->_handle =123;
- }
- //A new method to get the private member $_handle is added here
- public function handle()
- {
- return $this->_handle;
- }
- }
-
- print( "Handle = ".DatabaseConnection::get()->handle()."n" );
- print( "Handle = ".DatabaseConnection::get()->handle()."n" );
- ?>
-
Copy code
8Handle = 123
Handle = 123
[Finished in 0.1s]
Of these two examples, my personal preference is the second one
Four. Limit the number of instances that can be generated
-
- class DatabaseConnection {
- public static function get($persistent_id=0) {//Pass in an identifier
- static $db = array();//Change to array here
- if ( !array_key_exists($persistent_id, $db) ) {
- echo __LINE__;
- $db[$persistent_id] = new DatabaseConnection();
- }
- return $db[$persistent_id];
- }
-
- private $_handle = null;
-
- private function __construct() {
- $dsn = 'mysql://root:password@localhost/photos';
- $this->_handle =123;
- }
- //Add private member $_handle here Method
- public function handle() {
- return $this->_handle;
- }
- }
-
- print( "Handle = ".DatabaseConnection::get(1)->handle()."n" );
- print( "Handle = ".DatabaseConnection::get(2)->handle()."n" );
- print( "Handle = ".DatabaseConnection::get(2)->handle()." n" );
- ?>
-
Copy code
6Handle = 123
6Handle = 123
Handle = 123
[Finished in 0.1s]
In addition, using static method allows us to easily implement PHP's singleton mode.
Of course it is also possible to use global variable storage, but this approach is only suitable for smaller applications.
In larger applications, avoid using global variables and use objects and methods to access resources.
|