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 Extending Object-Oriented PHP Inheritance Extending a Class

Ole Vølund Skov Mortensen
Ole Vølund Skov Mortensen
27,841 Points

How come you can access the $db variable in collection Class?

OK, mabye i failed listening in the magic construct function class (here refers to a school class) but I fail to understand this concept. Where did the $db variable come from in Collection class. in the config file it add the connection: $db variable to the collection class. If the connection to the database was done in the config file. what's the connection class constructor function then doing?? I don't see a reference to this class any where obvious. Sorry, for this stupid question right now but i need to know to follow the logic of this.

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! In the config.php file you create a new database connection. Then at the very end you can see the creation of a new instance of Collection.

$directory = new Collection($db);

This creates a new instance of Collection with the new database connection you just made being passed into the constructor.

In Collection.php you have the constructor which takes a parameter and sets the private variable of $db to the thing that was passed in. In this case, the connection to the database.

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

This creates a new Collection with the value of $db being set to whatever was sent in by config.php.

Hope this clarifies things! :sparkles: