简体   繁体   中英

Have only one instance of a class

I was wondering how I can get one instance of the following db connection.

For example, lets say this is my class in the file Database.php

public class Database {
    public function __construct() {
      try {
            // PDO Here
            print("Connected!");
        } catch (PDOException $e) {
            die($e->getMessage());
        }
    }
}

index.php

Database();
Database();

Result

Connected!Connected!

I want to instantiate the class only once even if I call it twice.

You could use a static variable to assign the Database class to and then use a if statement to check whether that variable has been instantiated.

There are many ways of doing this, but this is how I would do.

Database.php

public class Database
{
    private static $instance;

    private function __construct()
    {
        try {
           // PDO Here
           print("Connected!");
        } catch (PDOException $e) {
           die($e->getMessage());
        }
    }

    public static function getInstance()
    {
        // Check is $_instance has been set
        if(!isset(self::$instance)) 
        {
            // Creates sets object to instance
            self::$instance = new Database();
        }

        // Returns the instance
        return self::$instance;
    }
}

index.php

 Database::getInstance();
 Database::getInstance();

Will only print "Connected!" once because the instance variable has been instantiated.

I recommend you to read Singleton Pattern if you haven't heard of it. Look at the example codes they show, its not in PHP but it should be easy to understand.

EDIT:

In case you want to make the getInstance function short you can do the following.

return !isset(self::$instance) ? self::$instance = new self : self::$instance;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM