当前位置:Gxlcms > PHP教程 > php单例模式(SingletonPattern)实例教程

php单例模式(SingletonPattern)实例教程

时间:2021-07-01 10:21:17 帮助过:14人阅读

  1. class DatabaseConnection {
  2. private static $db;
  3. private static $_handle = null;
  4. public static function get() {
  5. if ( self::$db == null ){
  6. echo __LINE__;
  7. self::$db = new DatabaseConnection();
  8. }
  9. return self::$_handle;
  10. }
  11. private function __construct() {
  12. $dsn = 'mysql://root:password@localhost/photos';
  13. self::$_handle = 123;
  14. }
  15. }
  16. print( "Handle = ".DatabaseConnection::get()."\n" );
  17. print( "Handle = ".DatabaseConnection::get()."\n" );
  18. ?>

9Handle = 123 Handle = 123 [Finished in 0.1s]

例2,php单例模式。

  1. class DatabaseConnection
  2. {
  3. public static function get()
  4. {
  5. static $db = null;//此处将示例1的静态成员变为静态变量
  6. if ( $db == null ){
  7. echo __LINE__;
  8. $db = new DatabaseConnection();
  9. }
  10. return $db;
  11. }
  12. private $_handle = null;//此处将表示示例1的静态去除
  13. private function __construct()
  14. {
  15. $dsn = 'mysql://root:password@localhost/photos';
  16. $this->_handle =123;
  17. }
  18. //此处新增获取私有成员$_handle的方法
  19. public function handle()
  20. {
  21. return $this->_handle;
  22. }
  23. }
  24. print( "Handle = ".DatabaseConnection::get()->handle()."\n" );
  25. print( "Handle = ".DatabaseConnection::get()->handle()."\n" );
  26. ?>

8Handle = 123 Handle = 123 [Finished in 0.1s] 这两个示例个人偏好第二个 四。限度可生成实例的个数

  1. class DatabaseConnection {
  2. public static function get($persistent_id=0) {//传入一个标识
  3. static $db = array();//此处改为数组
  4. if ( !array_key_exists($persistent_id, $db) ) {
  5. echo __LINE__;
  6. $db[$persistent_id] = new DatabaseConnection();
  7. }
  8. return $db[$persistent_id];
  9. }
  10. private $_handle = null;
  11. private function __construct() {
  12. $dsn = 'mysql://root:password@localhost/photos';
  13. $this->_handle =123;
  14. }
  15. //此处新增获取私有成员$_handle的方法
  16. public function handle() {
  17. return $this->_handle;
  18. }
  19. }
  20. print( "Handle = ".DatabaseConnection::get(1)->handle()."\n" );
  21. print( "Handle = ".DatabaseConnection::get(2)->handle()."\n" );
  22. print( "Handle = ".DatabaseConnection::get(2)->handle()."\n" );
  23. ?>

6Handle = 123 6Handle = 123 Handle = 123 [Finished in 0.1s] 补充,利用static静态化的方法使我们可以轻松地实现php的单例模式。 当然也可以使用全局变量存储,但是这种方法仅适用于较小的应用程序。 在较大的应用程序中,应避免使用全局变量,并使用对象和方法访问资源。

人气教程排行