php - How to share same connection with multiple instances of the object?

929

I was advised to rewrite how I handle connection, as it is now, my class creates new connection on every instance of the object. How would I change it to share connection between multiple objects created with this class?

/**
* This is Users class, deals with finding, updating, creating user
*/
class Users
{

    private $host   = DB_HOST;
    private $user   = DB_USERNAME;
    private $pass   = DB_PASSWORD;
    private $dbname = DB_NAME;

    private $conn;
    private $stmt;
    public  $error;

    function __construct()
    {
        $dsn = 'mysql:host='.$this->host.';dbname='.$this->dbname.';charset=utf8';
        $options = array(
            PDO::ATTR_EMULATE_PREPARES  => false,
            PDO::ATTR_PERSISTENT        => true,
            PDO::ATTR_ERRMODE           => PDO::ERRMODE_EXCEPTION
        );
        try {
            $this->conn = new PDO($dsn,$this->user,$this->pass,$options);
        } catch (PDOException $e) {
            $this->error = $e->getMessage();
        }
    }

    private function mysql_execute_query($sql,$params)
    {
        $this->stmt = $this->conn->prepare($sql);
        $this->stmt->execute($params);
        return $this->stmt;
    }

    public function find_user_by_provider_uid($provider,$provider_uid)
    {
        $sql = 'SELECT * FROM users WHERE provider = :provider AND provider_uid = :provider_uid LIMIT 1';
        $params = array(
            ':provider'     => $provider,
            ':provider_uid' => $provider_uid
        );
        $result = $this->mysql_execute_query($sql,$params);
        return $result->fetch(PDO::FETCH_ASSOC);
    }
}
714

Answer

Solution:

If you really need that, define your property asstatic:

private static $conn;

Of course, make sure that accessing to that will be done right (i.e. not via$this, but viaself (or class name) since it will be no longer belong to instance)

That, however, isn't a good practice: if you want manage connections - manage how many times you'll instantiate your class.

People are also looking for solutions to the problem: php - Merge two associative arrays of associative arrays and preserve all keys

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.