Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Best way to include PDO object from a separate file in a class?

Hello All,

I am currently trying to apply the skills I learnt here on a little project and I have run into the following little dilemma.

I have created a class that is in its own file and a database connection file that is also on its own file. How can I use the PDO instance (I called it $db) inside my class? Right now I have done the following:

<?php
    require_once($_SERVER['DOCUMENT_ROOT'] . '/lib/database.php');

    class MyClass
    {

      public function myFunction() 
      {
        global $db;
        // etc.
      }

    }
?>

This works, but I'm not sure whether this is the best way of doing this. Could anybody please enlighten me?

Thanks a lot for your time! :)

1 Answer

Hello,

You could try the following:

<?php

class MyClass {
   private $db;

   function __construct($conn) {
      $this->db = $conn;
   }
}

?>

This will allow you to pass in the connection instance when you instantiate the class.

$conn = new MyClass($db);

Hope this is what you are looking for.

Cheers!

That's just brilliant, thank you very much! :)