0

Possible Duplicate:
PHP and PDO class question

I was wondering if anyone could help I have a basic php PDO extend class and i wanted to use a global $db in other class to do all the mysql stuff. I can connect to database and that but just want to use a global variable which i can access in any class.

But I dont want to extend the database class with my new classes, i also don't want to pass the database connection var in the class constructor.

is there a way to do this?

here's some coding sample what i want to achive excuse any coding errors..

//--DATABASE CLASS
class Database Extends PDO {

    protected $database_hostname = DB_HOST;
    protected $database_username = DB_USER;
    protected $database_password = DB_PASSWORD;
    protected $database_name = DB_NAME;
    protected $database_type = DB_TYPE;

    public function __construct() {

        try {
            parent::__construct($this->database_type . ':host=' . $this->database_hostname . ';dbname=' . $this->database_name, $this->database_username, $this->database_password, array(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION));
        } catch (PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
        }
    }

}



//--TEST CLASS
class test1 {

    //--INSIDE MY FUNCTIONS I WANT TO BE ABLE TO USE A $db to do my msql stuff
    public function test1a() {

        $stmt = $db::prepare('SELECT * FROM table');
        $stmt->excute();
    }

}

//--TEST CLASS 2
class test2 {

    public function test2a() {

        $stmt = $db::prepare('SELECT * FROM table');
        $stmt->excute();
    }

}

//--CREATE THE DATABASE GLOBAL
 $db = new Database();
 $testers = new test2();

If i did the above i would get an error saying that $db is Undefined variable: db

Community
  • 1
  • 1

2 Answers2

1

Although I read that was not recommended, you can do the following: outside of all the classes (in the global scope) initialize your connection:
$db = new Database();
Then in every function where you need your Db connection, write this:
global $db;

Andre Polykanine
  • 3,291
  • 18
  • 28
1

When using $db inside a function, PHP expects the variable to be in the local function scope. To access the global variable, use either

  1. $GLOBALS['db']->prepare (important: Use -> instead of ::; calling prepare statically will not work), or
  2. global $db; $db->prepare(...);
helmbert
  • 35,797
  • 13
  • 82
  • 95
  • Thank you for help but could a make it a static class and return it as static var... not sure how i could do this.. – rwebdev Feb 03 '13 at 16:44