Just save the connection in a static variable:
private static $db = null; public static function getConnection() { if (!is_null(self::$db)) return self::$db; // ... self::$db = ...; return self::$db; }
However, it is capable of delivering pain as soon as the need arises for a second connection.
In your case (static classes), about the same can be done in client classes:
class Advt { private static $db; public static function setDB(DB $db){self::$db = $db;} public static function getAdvtList($page = 1) { //... self::$db->query(...); //... } } Advt::setDB(DB::getConnection());
Everything below is just my vision of how it should be.
It is better to store the connection in a DB instance, and by implementing a couple of methods for queries, work with it.
In classes whose existence without a connection to the base does not make sense, you can pass the base object to the constructor and save it in $this->db say.
class Db { private $config; private $connection; public function __construct() { $paramsPath = ROOT . '/config/db_params.php'; $this->config = include($paramsPath); } public function connect() { $dsn = "mysql:host={$this->config['host']};dbname={$this->config['dbname']}"; $this->connection = new PDO($dsn, $this->config['user'], $this->config['password']); $this->connection->exec("set names utf8"); } public function query($sql, $params) { if (!$this->connection) $this->connect(); // prepare/execute } public function rows($sql, $params) { // query/fetch } // fetch rows public function row($sql, $params) {} // fetch one row public function col($sql, $params, $col = 0) {} // fetch column public function cell($sql, $params, $col = 0) {} // fetch scalar value }
somecontroller.php
class A { protected $db; public function __construct(DB $db) {$this->db = $db;} public function getUser($id) { return $this->db->row('SELECT * FROM Users WHERE id = ?', [$id]); } }
class DB extends \PDO {...}if you write / use your wrapper over PDO. - Visman