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

Jonathan Söder
Jonathan Söder
5,771 Points

Passing PDO connection to a class

Hi!

I'm going over to PDO and I'm wondering, how do I actually pass a PDO connection to a class in another file.

File 1: Connection

//Error reports, remove before launch.
ini_set('display_errors', 'On');

//Put in level above root before launch
$ini_array = parse_ini_file("hidden/config.ini");

$host = $ini_array['Host'];
$database = $ini_array['Database'];
$username = $ini_array['Username'];
$password = $ini_array['Password'];

    try {
        $db = new PDO("mysql:host=$host; dbname=$database; charset=utf8", "$username", "$password");
        var_dump($db);
    }catch(Exception $e){
        echo "error: " . $e->getMessage();
    }

File2: Class with database methods

class DoStuff {

   function __construct(){
      //Here's where the DB connection should go I assume, so I'm always connected when calling a method. What do I pass in??? or rather, how do I pass the connection?
   }

   function getFromDb(){
      //Fetch info from DB
   }
}

Passing the connection directly to a method just yields undefined variable errors. Basically I want the connection in a file of its own, fetching the sensitive data from an ini file which is placed on a level above root. So far so good. I then want to pass the connection to a class constructor in another file so I automatically connect whenever I call a method.

I'm basically after this:

$magic = new DoStuff;
$magic -> getFromDb(); //This works, even though I've separated connection and class with methods containing queries into their own files.

1 Answer

Jake Lundberg
Jake Lundberg
13,965 Points

you can use your first file, i'll call it 'shared.php', and then use:

require("shared.php");

in each of the scripts that needs it... require will include this object defined in shared.php

Jonathan Söder
Jonathan Söder
5,771 Points

Ooops! I did NOT think of that. Thanks!