-1

Possible Duplicate:
Global or Singleton for database connection?

i have a database class in database.php then on the same file i create an object; $database = new Database(); Then i include this file into another file- this file has a class called Test inside Class Test has a method test_me. inside test_me method i want to access $connection variable of Database class. how can i do this?

this is what i've tried;

function test_me(){
  global $connection;
  //use $connection on another function..
}

this gives me an error undefined variable $connection . any idea what i'm doing wrong?

Community
  • 1
  • 1
guitarlass
  • 1,587
  • 7
  • 21
  • 45
  • Some people use `singleton`s, others use Dependency Injection. You could also look at persistent connections. – Jared Farrish Jun 17 '12 at 05:50
  • You could try `$GLOBALS['connection']` too, but I'd seriously rethink how your code is structured. You could also use a `dbconn()` function which returns a statically-declared `$connection` variable and use that in your functions (somewhat? [`singleton` pattern](http://stackoverflow.com/questions/130878/global-or-singleton-for-database-connection)). But DI with some code encapsulation is my suggestion for best practice. – Jared Farrish Jun 17 '12 at 05:54

2 Answers2

2

If you declare $connection a global variable, your code is ok.

But it is better to avoid using global variable. You could set the connection in the Test class.

An example is:

class Test {

  protected $connection;

  public function setConnection($connection) {
    $this->connection = $connection;
  }

  function test_me () {
    // use $this->connection.
    //...
  }
}
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • Dependency injection - probably the best approach if you're code is well-organized. – Jared Farrish Jun 17 '12 at 05:51
  • @JaredFarrish Yep, DI is easy for test. – xdazz Jun 17 '12 at 05:52
  • Y'know, and I've never figured it out, but there have been times when `global $var` didn't properly import. So I use `$GLOBALS['var']` IF necessary. Any comments appreciated on the validity of this approach. – Jared Farrish Jun 17 '12 at 05:57
  • hi, well my code is not ok for some reason, i did the same thing on another project and it worked . but this one cannot find `$connection`. however i tried your approach too, it didn't work- still cannot fine `$connection`. Are you sure using this coding part on my file will solve this? or do i have to edit another things? `$connection` is the database connection and it should be inside Database class. – guitarlass Jun 17 '12 at 15:38
  • @guitarlass If you set the right connection, my code will be ok. – xdazz Jun 18 '12 at 01:49
0

There are several ways of achieving this, something simple should be like

function test_me()
{
    global $database;

    echo $database->connection; // or do whatever you want with it
}
slash197
  • 9,028
  • 6
  • 41
  • 70