I understand that PDO cannot be serialized into sessions, I can use singleton where the PDO is accessed through instantiation like in this example Use of PDO in classes. I've compacted the code and remove exception handling for example sake with all the necessary details for PDO connection.
class Database
{
public $db;
private static $instance;
private function __construct()
{
$dsn = 'mysql:dbname=test;host=localhost;port=3306';
$this->db = new PDO($dsn, 'user', 'password');
echo 'You will see this when PDO is created or instantiated';
}
public static function getInstance()
{
if (!isset(self::$instance))
{
$object = __CLASS__;
self::$instance = new $object;
}
return self::$instance;
}
}
And then each page or script calls the static instance by using e.g:
$database = Database::getInstance();
$stmt = $database->db->prepare('SELECT * FROM table');
$stmt->execute();
Now this is all well and good but my understanding is that a new PDO is created every time the instance gets called. Is there a way, without using frameworks e.g. Zend Registry, to pass the PDO from page to page without creating a new PDO every time? I can't seem to find an answer to this question. Although it is a single instance it still seems rather redundant reconnecting to the database on every page. Thanks.
Solved
I think in the end it is a limitation of PHP, what I'm asking for cannot really be done. Thanks all for your help, appreciate it.