Take the 2-minute tour ×

I've got a PHP project with many classes, and a PDO Wrapper class that I got off the web that seems pretty good:


My classes look like this now:

class product {
__constructor($id = 0) {
//mysql_query and store the product row in $this->row;

edit($array) {
//another obvious mysql_query...

So they're very simple and I want to move all the mysql_query's to PDO for security. I've got the variable:

$db = new pdo('localhost', 'user', 'pass');

Working correctly defined in the top line of my include file, before the classes. However, I don't want to have to write:

global $db;

At the start of every function. I considered changing the __construct() function to be something more like:

__construct($id = 0, $db = null) {
$this->db = $db;

And then referencing from there, but the problem with that is that I then have to change every constructor in my whole website. Is there a way to solve this such that I am able to do the minuimum amount of editing the already existing code?

share|improve this question
add comment

3 Answers

up vote 2 down vote accepted

Make all your model classes inherit from a base model class, then define a static variable $db in your base class, and use it in the inherited classes.

class BaseModel {
  public static $db = NULL;

class UserModel extends BaseModel {
  public function create() {
    echo "Use the static variable: " . static::$db . "\n";

BaseModel::$db = "new PDO object";


Use the static variable: new PDO object
share|improve this answer
It's not better than global variables –  zerkms Aug 5 '12 at 12:41
It's better in a sense that you don't have to say global $db inside of every function, and it's only "global" in BaseModel and its descendants rather than everywhere. –  Gary G Aug 5 '12 at 12:44
This appears better in that I would only have to make a tiny "BaseModel" class and then type "extends BaseModel" at the end of ten class files, which would make it essentially backwards compatible while I change all the database calls over. Thanks! –  Andreas Christodoulou Aug 5 '12 at 13:45
add comment

as you said there is a PDO class so in every other classes easily you can make an instance of your PDO class. first include the PDO class in anywhere you need


then make instances

$a=new PDAclass;
share|improve this answer
add comment

You say the $db is defined in your include file. so just include the file and you'll have access to that parameter.

share|improve this answer
add comment

Your Answer


