0

I have a class that extends PDO:

class MyPDO extends PDO {

}

Which has some helper methods such as insert() and update(). However, when used in addition to a framework, I would normally have access to an already initialised PDO instance.

How would I instantiate MyPDO so it extends the already existing PDO instance instead of creating a new one?

$pdo; # An already existing PDO connection.

$myPdo = new MyPDO(); # Creates a new PDO object

# I want to create a new MyPDO which extends $pdo

$myPdo = new MyPDO() + $pdo; # How would I accomplish this? Reflection?

I basically do not want to have more than one PDO connection but want the additional functionality of MyPDO. Can this be done? Maybe with Reflection?

Ozzy
  • 10,285
  • 26
  • 94
  • 138
  • 3
    [Composition over inheritance](http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance). I've never been a fan of extending core database drivers to create database abstraction layers. – Mark Jan 28 '15 at 09:57

1 Answers1

0

Simplest solution is to pass $pdo in your class

<?php

    class MyPDO {
        public $pdo;
        public function __construct($pdo) {
           $this->pdo = $pdo;
        }

        // your Methods use in the class $this->pdo->foo
   }
  $myPdo = new MyPDO($pdo);

Other way ... you extends direct mypdo on pdo and build the instance $pdo from mypdo

class MyPDO extends PDO {
    public function __construct() {
       parent::__construct();
    }
    #Your additional methodes
}
$pdo = new MyPDO();
donald123
  • 5,638
  • 3
  • 26
  • 23
  • In your first example, MyPDO would not be an instance of PDO and I would have to create __call method to proxy all method calls to the pdo property. The second example would not be able to use the existing PDO instance. – Ozzy Jan 28 '15 at 10:01