-
-
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" );
- ?>
-
复制代码
9Handle = 123
Handle = 123
[Finished in 0.1s]
例2,php单例模式。
-
-
class DatabaseConnection
- {
- public static function get()
- {
- static $db = null;//此处将示例1的静态成员变为静态变量
- if ( $db == null ){
- echo __LINE__;
- $db = new DatabaseConnection();
- }
- return $db;
- }
-
- private $_handle = null;//此处将表示示例1的静态去除
-
- private function __construct()
- {
- $dsn = 'mysql://root:password@localhost/photos';
- $this->_handle =123;
- }
- //此处新增获取私有成员$_handle的方法
- public function handle()
- {
- return $this->_handle;
- }
- }
-
- print( "Handle = ".DatabaseConnection::get()->handle()."\n" );
- print( "Handle = ".DatabaseConnection::get()->handle()."\n" );
- ?>
-
复制代码
8Handle = 123
Handle = 123
[Finished in 0.1s]
这两个示例个人偏好第二个
四。限度可生成实例的个数
-
-
class DatabaseConnection {
- public static function get($persistent_id=0) {//传入一个标识
- static $db = array();//此处改为数组
- 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;
- }
- //此处新增获取私有成员$_handle的方法
- 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" );
- ?>
-
复制代码
6Handle = 123
6Handle = 123
Handle = 123
[Finished in 0.1s]
补充,利用static静态化的方法使我们可以轻松地实现php的单例模式。
当然也可以使用全局变量存储,但是这种方法仅适用于较小的应用程序。
在较大的应用程序中,应避免使用全局变量,并使用对象和方法访问资源。
|